1

I am using following query/piece of code, for updating a MySQL database via PHP -

$sql = "UPDATE test_table SET lastname='ram' where id=1";
$result = mysql_query($sql); 
echo $result;

the problem with this is, the PHP output is 1 even if there was no updating done. for e.g. in my case, there is no row that contains id=1 so when I run this query in phpmyadmin it says 0 rows affected, while the using the same query in PHP is returning 1.

My question is - how to know, if the update was done ($result = 1) or not ($result = 0) without using a new select query to check the change?

6
  • 1
    First - migrate to more up-to-date API. If not - read manual and find mysql_affected_rows or mysql_info. Commented Nov 1, 2014 at 19:24
  • @u_mulder sorry sir, i am not even a computer student, I am a medical doctor who wanted to learn something other than human body in free time.. that's why I asked this stupid question. Commented Nov 1, 2014 at 19:29
  • What does that have to do with anything? As a medical doctor you should be more than capable of doing your own research. And what he indicated was that you shouldn't be using the mysql_ APIs anymore. Commented Nov 1, 2014 at 19:33
  • 1
    @JonathonReinhart yes sir I agree with you and u_mulder, that's why I upvoted him too. But there is a limit for doing research. If it's a case of any surgery I would be far too much happy to read 100s of Medical Books. But time does not allow me learn every programming language., like I spend time to learn to do surgery. That's why I asked this question on stacksoverflow Commented Nov 1, 2014 at 19:38
  • 1
    If you're spending the time to learn PHP and MySQL, then find a newer resource that teaches you the mysqli or PDO APIs. People who refuse to heed the warnings of experienced developers are the ones who contribute to the overall insecurity of the Internet. If you have the time to learn, you have the time to lean right. Commented Nov 2, 2014 at 23:12

1 Answer 1

4

mysql_query returns true when an update succeeds (i.e., runs without an error, regardless of how many rows it did or did not update). If you want the number of rows you've actually updated, you need to call mysql_affected_rows:

$sql = "UPDATE test_table SET lastname='ram' where id=1";
if (mysql_query($sql)) {
    $result = mysql_affected_rows();
    echo $result;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you sir, works perfect. I will accept it as answer, as soon as time limit of stackoverflow for accepting answer allows me to.
@Mureinik And shame on you for not even mentioning in your answer that the APIs you are describing have been obsolete for some time now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.