Question

What I am doing is editing the data of MySQL data using PHP using form.

I have two text field as name and mobile number. When I click on edit, I get same data in text field and below I have Save button. When I do changes I get response as done, but when I click edit and don't do any changes in text field and click Save I get response as fail.

Below is code for SAVE button.

$sql = mysql_query("
    UPDATE userInfo SET fullName='$fullName', 
    mobileNumber='$mobileNumber' 
    WHERE id=$tagNumberId"
);

if (mysql_affected_rows()==1) {
    echo "done";
} else {
    echo "fail";
}

I am worried about mysql_affected_rows().

Above makes me think that if data is same in UPDATE statement, mysql_affected_rows() will return 0 and if data is not same in UPDATE statement, mysql_affected_rows() will return 1.

Is this right? If it is right, how to deal with whether the update is done or not?

Was it helpful?

Solution

Use mysqli_info, just after executing the query

$string = mysqli_info ( $link );

returns a string having the relevant information, like for UPDATE

Rows matched: 40 Changed: 40 Warnings: 0

in your case, one row updated but no change, you should get

Rows matched: 1 Changed: 0 Warnings: 0

You can retrieve the value from

preg_match("/Rows matched: (\d+)/", $string, $matches);
$number_of_rows = intval($matches[1]);

OTHER TIPS

It's right mysql behavior of UPDATE. But you can use some wiered trick if you really want this.

$sql = mysqli_query("UPDATE userInfo SET id=@id:=id
                    fullName='$fullName',
                    mobileNumber='$mobileNumber'
                    WHERE id=$tagNumberId");
$result = mysqli_query($link, 'select @id');
if (array(null)!==mysqli_fetch_row($result)) {
    echo "done";
} else {
    echo "fail";
}

P.S. You MUST use prepared statements for yours applications.

P.P.S. with this method you can't recognize count, but there is no need if you use update on id.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top