Php 逗号分隔字符串的比较和mysql列的更新

Php 逗号分隔字符串的比较和mysql列的更新,php,mysql,Php,Mysql,我有一个php逗号分隔字符串$string=a,b,c 我在mysql中有一个列,其中有b、c、d项 我想将列更新为a、b、c、d您真的不应该在数据库中的一个字段中存储多个值-即使可以执行您想要的操作,但效率非常低。考虑规范化您的模式,并对两个表使用一对多关系 如果你必须这样做,那么你可以做如下的事情。请注意,必须将错误处理添加到此代码中 //connect to the database and read existing data $dbh = new PDO(CONNECT_STRING,

我有一个php逗号分隔字符串$string=a,b,c

我在mysql中有一个列,其中有b、c、d项
我想将列更新为a、b、c、d

您真的不应该在数据库中的一个字段中存储多个值-即使可以执行您想要的操作,但效率非常低。考虑规范化您的模式,并对两个表使用一对多关系

如果你必须这样做,那么你可以做如下的事情。请注意,必须将错误处理添加到此代码中

//connect to the database and read existing data
$dbh = new PDO(CONNECT_STRING, USERNAME, PASSWORD);
$dbs = $dbh->query("select data_string from my_table where id=1");
$row = $dbs->fetch(PDO:FETCH_NUM);
$dbs->closeCursor();

//strip parentheses and convert string to array
$cur_data = str_getcsv(substr($row[0], 1, -1));

//strip parentheses and convert new data to array
$string = "(a,b,c)";
$add_data = str_getcsv(substr($string, 1, -1));

//merge existing and new data eliminating duplicates
$new_data = array_unique(array_merge($cur_data, $add_data));

//create new csv string for the merged data
$output = fopen('php://output', 'w');
ob_start();
fputcsv($output, $new_data);
fclose($output);
$value = ob_get_clean();

//update database table with new csv string with parentheses
$dbs = $dbh->prepare("update my_table set data_string=? where id=?");
$dbs->execute(array("($value)", 1));
$dbs->close();

看看需要做多少不必要的工作?我真的敦促你重新设计你的模式。

我想这就是你想要的

<?php
$string = "b, c, d";
$pieces = explode(",", $string);

for($index=count($pieces); $index>0; $index-- ){
    $pieces[$index] = $pieces[$index-1];
}

$pieces[0] = "a";
$string = implode(", ", $pieces);
echo $string;
?>

现在您知道了线索。

感谢您的编辑,现在我们可以理解:像这样的问题是您不应该以这种方式在数据库中存储列表的原因。从数据库中获取旧值,删除括号,将字符串分解为数组,将新值与数组合并,将数组内爆为字符串,用括号将其包裹,然后更新数据库。
$string = '(a,b,c)';
$column = '(b,c,d)';

$string = substr($string, 1, -1);
$column = substr($column, 1, -1);

$string = explode(',', $string);
$column = explode(',', $column);

$result = array_unique(array_merge($string, $column), SORT_STRING);
$result = '(' . implode(',', $result) . ')';