简体   繁体   English

PHP&Mysql数据库更新问题

[英]PHP & Mysql database updating problem

For some reason when I changed my php code from mysql to mysqli everything got messed up. 由于某些原因,当我将php代码从mysql更改为mysqli时,一切都搞砸了。

For example, when a user enters a rating my mysql table updates twice by entering one new row and updating the correct row. 例如,当用户输入一个等级时,我的mysql表通过输入一个新行并更新正确的行来更新两次。 I was wondering how do I correct this problem so it only updates the new row and checks to see if there is no row it enters one? 我想知道如何解决此问题,使其仅更新新行并检查是否没有行输入?

PHP code 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); 
    }
}

old php code 旧的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); 
    }
}

怎么样

if (mysqli_affected_rows($dbc) ==0){

You should instead combine the two statements. 相反,您应该合并这两个语句。 This would require you to have a PRIMARY KEY, perhaps named id. 这将要求您具有一个主键,可能名为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); 
}

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

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