views:

26

answers:

2

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.

+1  A: 

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

Lex
+1 Good educated guess given the lack of information in the question.
Mark Byers
Thanks for the suggestion, I am going to give it a try. The code was looking proper in my editor, but had touble when I pasted it here..
happyhardik
Okay, in that case you ignore my little note :)
Lex
Ok it works.. thank you guys!
happyhardik
A: 

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.

Crozin