出于某种原因,当我将我的php代码从mysql更改为mysqli时,一切都搞砸了。
例如,当用户输入评级时,我的mysql表会通过输入一个新行并更新正确的行来更新两次。我想知道如何纠正这个问题所以它只更新新行并检查它是否没有进入一行?
PHP代码
// function to insert rating
function rate(){
$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$text = strip_tags($_GET['rating']);
$update = "update vote set counter = counter + 1, value = value + ".$_GET['rating']."";
$result = mysqli_query($dbc,$update);
if(mysqli_affected_rows() == 0){
$insert = "insert into vote (counter,value) values ('1','".$_GET['rating']."')";
$result = mysqli_query($dbc,$insert);
}
}
旧的PHP代码
// function to insert rating
function rate(){
$text = strip_tags($_GET['rating']);
$update = "update vote set counter = counter + 1, value = value + ".$_GET['rating']."";
$result = mysql_query($update);
if(mysql_affected_rows() == 0){
$insert = "insert into vote (counter,value) values ('1','".$_GET['rating']."')";
$result = mysql_query($insert);
}
}
答案 0 :(得分:0)
尝试这个怎么样
if (mysqli_affected_rows($dbc) ==0){
答案 1 :(得分:0)
您应该将两个语句组合起来。这将要求您拥有一个PRIMARY KEY,可能名为id。
// function to insert rating
function rate() {
$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$text = strip_tags($_GET['rating']);
$update = sprintf('INSERT INTO vote SET
id = 1,
counter = 1,
value = %1$d
ON DUPLICATE KEY UPDATE
counter = counter + 1,
value = value + %1$d',
$text);
mysqli_query($dbc,$update);
}