简体   繁体   English

使用PHP更新多个SQL字段

[英]Updating multiple SQL fields with PHP

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和$ data取自后填充数组:

$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: 我尝试了2种方法:

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. 第一个SQL函数不起作用(就像INSERT一样烦人),第二个SQL函数仅更新数组中的一个值。

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 UPDATE的语法是使用SET名称=值,名称=值,... 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. 另外,正如其他人指出的那样,不建议使用mysql_query()。 There is http://php.net/manual/en/book.mysqli.php , and better yet (apparently), http://php.net/manual/en/book.pdo.php . http://php.net/manual/en/book.mysqli.php ,还有(显然)更好的http://php.net/manual/en/book.pdo.php They're a bit more complicated to use, but well worth the small learning curve. 它们使用起来有点复杂,但是值得学习。

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

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