简体   繁体   English

mysql 如果列存在则更新表(foreach)

[英]mysql update table if column exists (foreach)

I've been playing with this:我一直在玩这个:

foreach($textnode as $key => $value) {

$value = stripslashes($value);
 $value = mysql_real_escape_string($value, $con);

 mysql_query("INSERT INTO paragraphs (paragraphs, url)
 VALUES ('$value', '$url')");



}

I've been trying to update the column "paragraphs" for where the url already exists我一直在尝试更新 url 已经存在的“段落”列

This doesn't seem to work well as it just replaces each row in paragraphs with the 1st paragraph.这似乎效果不佳,因为它只是用第一段替换段落中的每一行。 (repeats it over and over again) (一遍又一遍地重复)

mysql_query("UPDATE paragraphs SET paragraphs = '$value'
 WHERE url = '$url'"); 

Is the url field unique? url字段是否唯一?

If not, add a UNIQUE constraint on it and use INSERT INTO. . . ON DUPLICATE KEY UPDATE如果不是,则在其上添加一个 UNIQUE 约束并使用INSERT INTO. . . ON DUPLICATE KEY UPDATE INSERT INTO. . . ON DUPLICATE KEY UPDATEINSERT INTO. . . ON DUPLICATE KEY UPDATE with something like this:INSERT INTO. . . ON DUPLICATE KEY UPDATE有这样的东西:

 mysql_query("INSERT INTO paragraphs (paragraphs, url)
                VALUES ('$value', '$url')
              ON DUPLICATE KEY
                UPDATE paragraphs = '$value'
             ");

or (do you want to "append" the new '$value' when url already exists?):或者(当url已经存在时,你想“附加”新'$value'吗?):

 mysql_query("INSERT INTO paragraphs (paragraphs, url)
                VALUES ('$value', '$url')
              ON DUPLICATE KEY
                UPDATE paragraphs = CONCAT(paragraphs, '$value')
             ");

Try running the query尝试运行查询

SELECT paragraphs, url
FROM   paragraphs;

to see what your table really contains.看看你的桌子真正包含什么。 It may be that you've put in all the same URLs into your table.可能是您已将所有相同的 URL 放入表中。 Which would explain the update behavior.这将解释更新行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM