简体   繁体   English

新项目在列末尾添加两次

[英]The new item is added twice at the end of the column

I am trying to update the store column by adding new item (string) to the end of the column, But what happens is the new item is added twice at the end of the column, This is the code:我正在尝试通过将新项目(字符串)添加到列的末尾来更新存储列,但是会发生什么是在列的末尾添加了两次新项目,这是代码:

$query = "SELECT * FROM users";
$result = $conn->query($query);

while($row = $result->fetch_assoc()){

$item = 'item_name';
$store = $row['store'];
$newstore = $store . '|' . $item;

echo 'newstore : ' . $newstore . '<br>'; // It looks normal : store|item
    
$sql = "UPDATE users SET store='" . $newstore . "' WHERE username='" . $row['username'] .  "'";
$conn->query($sql); 
}

In in the database I find: store|item|item在数据库中我找到: store|item|item

Rather than reading the entire table and looping through it with PHP, run just a single UPDATE query to concatenate the extra data onto the column.:与其读取整个表并使用 PHP 循环遍历它,不如只运行一个 UPDATE 查询将额外的数据连接到列上:

$item = 'item_name';
$query = "UPDATE users SET store=concat(store,'|','$item')";
$result = $conn->query($query);

Note: this form is potentially open to SQL injection if you can't trust the value in $item .注意:如果您不信任$item中的值,则此表单可能对 SQL 注入开放。 You'd do better to use a prepared query if that's the case.如果是这种情况,您最好使用准备好的查询。

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

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