tags:

views:

65

answers:

2

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); 
    }
}
A: 

how about trying this

if (mysqli_affected_rows($dbc) ==0){
This should be done automatically by the function (so says the manual). Source: http://php.net/manual/en/function.mysql-affected-rows.php
AntonioCS
A: 

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