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

问题描述:

我基本上只是试图更新我的表中的多个值。什么是最好的方式去做这件事?下面是当前的代码:PHP:在单个查询中更新多个MySQL字段

​​

的其他更新我想包括是:

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

谢谢!

用逗号分离加入您的多列:

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

但是,你不消毒的投入?这意味着任何黑客都可能破坏你的数据库。看到这个问题:What's the best method for sanitizing user input with PHP?

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

逗号分隔值:

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

OK,但没有给予好评因为你忘了指出这种方法的明显缺陷。 :) – 2011-03-10 00:49:58

如果您使用的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)); 

我想你可以使用:

$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();