Sorry in advance for my amateur knowledge. I'm creating the basics of a user a database, I have registering working fine fine but I cannot get my update function working correctly.
Register function
mysql_query("INSERT INTO `users` ($fields) VALUES ($data)");
where $fields and $data are taken from a post filled array:
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
Update function
However using this method for updating records does not work. I have tried 2 methods:
mysql_query("UPDATE `users` SET ($fields) VALUES ($data) WHERE `user_id` = $user_id");
and
mysql_query("UPDATE `users` SET $fields = $data WHERE `user_id` = $user_id");
The first SQL function does not work (annoying as it does of INSERT) and the second one only updates one value from my array.
Can someone correct me on how this should be done? For info my array is as follows:
$save_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'email' => $_POST['email'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'bio' => $_POST['bio']
);
The syntax for UPDATE is to use SET name=value, name=value, ... http://dev.mysql.com/doc/refman/5.0/en/update.html
So try this:
// Prepare the name-value pairs for the SET clause.
$set = array();
foreach ($register_data as $key => $value) {
$set[] = "`$key` = '$value'";
}
$set = implode(', ', $set);
// Run the query.
mysql_query("UPDATE `users` SET $set WHERE `user_id` = $user_id");
As a side note, as others have pointed out, mysql_query() is not recommended. There is http://php.net/manual/en/book.mysqli.php , and better yet (apparently), http://php.net/manual/en/book.pdo.php . They're a bit more complicated to use, but well worth the small learning curve.
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.