我有以下代码:
$pdo = new PDO('mysql:host=localhost:3306;dbname=web190_db8', 'web190_8', 'password');
$statement = $pdo->prepare("UPDATE channelbro_rss SET links = ? WHERE channel = ?");
$statement->execute(array($links_new, $channel));
但是如何将$links_new
设置为数据库中links
的当前值,再加上一个新值?
例如:
数据库中links
的值为test
。首先,我想要回显此值,然后将links
的值更新为当前值(test
)加上另一个变量(以逗号分隔)。例如:将links
更新为test, new
。如果我再次执行此操作,它会将其更新为test, new, hello
(新值始终为$new
)。
答案 0 :(得分:5)
通过这样添加你希望修改旧值的值更简单。
concat()
函数的名称建议将新字符串连接到列的现有内容上。
$pdo = new PDO('mysql:host=localhost:3306;dbname=web190_db8', 'web190_8', 'password');
// If you want to see the value of links before you amend it
// as your requested, then you will have to get it as a seperate
// SELECT query
$stmt = $pdo->prepare("SELECT links FROM channelbro_rss WHERE channel = ?");
$stmt->execute( array($channel) );
$old_links = $stmt->fetchColumn(0);
echo $old_links;
$statement = $pdo->prepare("UPDATE channelbro_rss SET links = concat(links, ?) WHERE channel = ?");
$concat_text = ', new';
$statement->execute(array($concat_text, $channel));
// If you want to see the value of links AFTER you amend it
// then you will have to get it as a seperate SELECT query also
$stmt = $pdo->prepare("SELECT links FROM channelbro_rss WHERE channel = ?");
$stmt->execute( array($channel) );
$old_links = $stmt->fetchColumn(0);
echo $old_links;
答案 1 :(得分:3)
像这样更新您的查询:
$statement = $pdo->prepare("UPDATE channelbro_rss SET links = concat(links, ? ) WHERE channel = ?");
答案 2 :(得分:1)
您可以使用 Mysql CONCAT
功能;这是
CONCAT(STR1,STR2,...)
返回连接参数产生的字符串。可以 有一个或多个参数。如果所有参数都是非二进制字符串, 结果是一个非二进制字符串。如果参数包含任何二进制文件 字符串,结果是二进制字符串。数字参数是 转换为等效的非二进制字符串形式。
这是您要查找的查询字符串:
$pdo = new PDO('mysql:host=localhost;dbname=web190_db8', 'web190_8', 'password');
$statement = $pdo->prepare("UPDATE channelbro_rss SET links = CONCAT(links,', ', ?) WHERE channel = ?");# result: test, new, hello
$statement->execute(array($links_new, $channel));
还有CONCAT_WS(separator,str1,str2,...)
。检查mysql文档here以获取更多信息。