简体   繁体   中英

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.

my php code:

<?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.

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.

Or you implement a update logic inside php and detect if there already is an entry inside the table with the same username.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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