PHP:在单个查询中更新多个 MySQL 字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5254173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:45:31  来源:igfitidea点击:

PHP: Update multiple MySQL fields in single query

phpmysqlsqlsql-update

提问by Chris

I am basically just trying to update multiple values in my table. What would be the best way to go about this? Here is the current code:

我基本上只是想更新表中的多个值。解决这个问题的最佳方法是什么?这是当前的代码:

$postsPerPage = $_POST['postsPerPage'];
$style = $_POST['style'];

mysql_connect ("localhost", "user", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db");

mysql_query("UPDATE settings SET postsPerPage = $postsPerPage WHERE id = '1'") or die(mysql_error());

The other update I want to include is:

我想包括的另一个更新是:

mysql_query("UPDATE settings SET style = $style WHERE id = '1'") or die(mysql_error());

Thanks!

谢谢!

回答by Fosco

Add your multiple columns with comma separations:

用逗号分隔添加多列:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

但是,您没有对输入进行消毒??这意味着任何随机黑客都可能破坏您的数据库。请参阅此问题:使用 PHP 清理用户输入的最佳方法是什么?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

另外,样式是数字还是字符串?我假设一个字符串,所以它需要被引用。

回答by Christian

Comma separate the values:

逗号分隔值:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

回答by Phan Van Linh

If you are using pdo, it will look like

如果您使用的是 pdo,它看起来像

$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));

回答by CONvid19

I guess you can use:

我想你可以使用:

$con = new mysqli("localhost", "my_user", "my_password", "world");
$sql = "UPDATE `some_table` SET `txid`= '$txid', `data` = '$data' WHERE `wallet` = '$wallet'";
if ($mysqli->query($sql, $con)) {
    print "wallet $wallet updated";
}else{
    printf("Errormessage: %s\n", $con->error);
}
$con->close();