Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql_affected_rows() always returns 1 even though no row was updated

Tags:

mysql

count

row

What I am trying to do is: (programmatically)

Update status where id is something, if no rows where updated, give error: we cannot find the record with id something, otherwise give message success.

Here I am using mysql_affected_rows() to know if a row was updated or not, but it always return 1, so the user gets a success message, even though there was no row updated.

Can anyone tell me what could it be?

Here's the code:

   function update_sql($sql) {


  $this->last_query = $sql;

  $r = mysql_query($sql);

  if (!$r) {
     $this->last_error = mysql_error();         
     return false;
  }      
  $rows = mysql_affected_rows();
  if ($rows == 0) return true;  // no rows were updated
  else return $rows;  }

This code returns 1.

like image 530
happyhardik Avatar asked May 15 '10 14:05

happyhardik


2 Answers

That is because true will print out as "1" if you use echo. For debugging try using var_dump(), or let your function return 0 (which seems to me, in this case, the better option).

One little note; I think you should try to make your code a bit more readable (if the code in your question has the same layout as the code in your file). Try to indent code blocks, use separate lines for closing curly brackets, etc...

like image 65
rael_kid Avatar answered Sep 24 '22 00:09

rael_kid


This is just a guess...

Maybe your function works as excepted? Maybe this piece of code if ($rows == 0) return true; works fine, and returns true but you treat that value as integer (boolean true can be displayed as 1)? Do: var_dump(uddated_sql('YOUR QUERY')) and check whether it returns boolean true or integer 1 value.

like image 32
Crozin Avatar answered Sep 22 '22 00:09

Crozin