1

I use the code to update data in mysql.But it always echo "sucess " whatever $id equal to any integer.

$id=isset($_GET['id'])?$_GET['id']+0:0;
$sql="update user set age=50 where id=".$id;
$result=mysql_query($sql,$con);
if($result)
    echo "update sucess<br />";
else
    echo "update failed";
picture
  • 13
  • 4

1 Answers1

2

You should use mysql_affected_rows() instead.

So that an you'll know that it made changes you want.

Obligatory note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Here's what it will look like in using mysqli:

if(isset($_GET['id'])) {
    $con = new mysqli('localhost', 'username', 'password', 'database_name');
    $id = $_GET['id'];
    $sql = 'UPDATE user SET age = 50 WHERE id = ?';
    $update = $con->prepare($sql);
    $update->bind_param('i', $id);
    $update->execute();

    if($update->affected_rows > 0) {
        echo 'updated';
    } else {
        echo 'nothing';
    }
}
Community
  • 1
  • 1
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • Nice layout ;) - and I love the *"Here's what it will look like in using mysqli:"* - Now if only Stack would have something like SQLfiddle. – Funk Forty Niner Nov 06 '14 at 16:59
  • @Fred-ii- yeah, i wish they would include a php and sql feature also in the stack snippet :D – Kevin Nov 07 '14 at 00:05
  • @Fred-ii- actually that deprecation template is from Second Rikudo's answer. bookmarked it also :D http://stackoverflow.com/a/12860140/3859027 – Kevin Nov 07 '14 at 00:08
  • I meant as a "general" layout, the looks of it. I think it's my graphical side talking lol – Funk Forty Niner Nov 07 '14 at 01:02