Php mysqli affected rows return wrong result after delete statement

I have a function to remove a row from my table and I like to return true if the row existed previously. I am using the following function:

$mysqli = $this->mysqli;

$stmt = $mysqli->prepare("DELETE FROM active_clients WHERE token LIKE ?");
$stmt->bind_param('s', $token);
$stmt->execute();
if($stmt->affected_rows < 1){
    $stmt->close();
    return false;
}
$stmt->close();
return true;

      

It also worked on my localhost, but when I went to the server, it didn't return the correct result. affected_rows always returns 0, but the row is removed as it should. How can it be? Can there be a problem with the php version? I am running 5.4 locally and on a real server 5.3 ... Or is it also possible that it has something to do with the database or server configuration?

+3


source to share


2 answers


Try the following:



$mysqli = $this->mysqli;

$stmt = $this->mysqli->prepare("DELETE FROM active_clients WHERE token LIKE ?");
if(!$stmt){
    die('prepare() failed: ' . $mysqli->error);
}else{
    $stmt->bind_param('s', $token);

    if($stmt->execute()){
       $stmt->store_result();
        if($stmt->affected_rows < 0){
            $stmt->close();
            return false;
        }else{
            $stmt->close();
            return true;    
        }
    }else{
        die('execute() failed: ' . $mysqli->error);
    }


}

      

+2


source


If the last query was a DELETE query without a WHERE clause, all records will be deleted from the table, but this function will return zero with MySQL versions prior to 4.1.2.

Check your Mysql version.



Resource: http://php.net//manual/en/function.mysql-affected-rows.php

-1


source







All Articles