简体   繁体   中英

PHP & Mysql database updating problem

For some reason when I changed my php code from mysql to mysqli everything got messed up.

For example, when a user enters a rating my mysql table updates twice by entering one new row and updating the correct row. 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

// 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

// 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.

// 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); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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