开发者

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

开发者 https://www.devze.com 2022-12-30 04:18 出处:网络
What I am trying to do is: (programmatically) Update status 开发者_C百科where id is something, if no rows where updated, give error: we cannot find the record with id something, otherwise give messag

What I am trying to do is: (programmatically)

Update status 开发者_C百科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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号