简体   繁体   English

如果列中有相同的名称,则更新行中的值(MySQL中为PHP)

[英]Update values in a row if there is a same name in a column (with PHP in MySQL)

I have a database with three columns: ID, userName, feedback I want the feedback value to be updated when the userName is same. 我有一个包含三列的数据库:ID,用户名,反馈我希望当用户名相同时更新反馈值。

my php code: 我的php代码:

<?php
conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['name'];
$value2 = $_POST['message'];
$sql = "INSERT INTO js (userName, feedback) VALUES('$value', '$value2');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
};

$conn->close();
?>

If you want to do it with mysql you first of should define a unique index on the userName column. 如果要使用mysql,首先应在userName列上定义一个唯一索引。

ALTER TABLE js
ADD CONSTRAINT u_userName UNIQUE (userName)

The edit your insert query like this: 像这样编辑您的插入查询:

INSERT INTO js (userName, feedback) VALUES ('$value', '$value2')
  ON DUPLICATE KEY UPDATE feedback=VALUES(feedback);

Now if the duplicate key violation is hit by mysql, the value for feedback will be updated while inside the row where your username equals. 现在,如果mysql遇到重复的键冲突,则在用户名相等的行内,将更新反馈值。

Or you implement a update logic inside php and detect if there already is an entry inside the table with the same username. 或者,您在php中实现更新逻辑,并检测表中是否已经存在具有相同用户名的条目。

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

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