2011-03-10 68 views
14

我基本上只是試圖更新我的表中的多個值。什麼是最好的方式去做這件事?下面是當前的代碼:PHP:在單個查詢中更新多個MySQL字段

​​

的其他更新我想包括是:

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

謝謝!

回答

44

用逗號分離加入您的多列:

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

但是,你不消毒的投入?這意味着任何黑客都可能破壞你的數據庫。看到這個問題:What's the best method for sanitizing user input with PHP?

另外,風格是數字還是字符串?我假設一個字符串,所以它需要引用。

6

逗號分隔值:

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

OK,但沒有給予好評因爲你忘了指出這種方法的明顯缺陷。 :) – 2011-03-10 00:49:58

1

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

我想你可以使用:

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