Search code examples
phprowcountmysql-num-rows

Is using mysql_num_rows (rowCount in PDO) necessary in update or insert query?


Should I be using mysql_num_rows (rowCount in PDO) in update or insert query? Currently, my code looks likes this,

public function update_username(){
    $q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
    $r = $db->query($q);
    if($r){
        $message = "Updated successfully";
        return $message;
    }else{
        return false;
    }
}

Should I change it to like this?

public function update_username(){
    $q = "UPDATE usertable SET username = '$user_name' WHERE id = '$user_id' LIMIT 1";
    $r = $db->query($q);
    if($r){
        $num = $r->rowCount();
        if($num == 1){
            $message = "Updated successfully";
            return $message;
        }else{
            $message = "An error occurred";
            return $message;
        }
    }else{
        return false;
    }
}

Normally, query goes through without any error, so I shouldn't worry about it too much, but which one would be a better coding practice? Or do you suggest something else?

Thanks so much in advance!


Solution

  • Actually the two codes do something different.

    The first one will print "Update success" if the query was successfully executed. But a query can be successfully executed also without affecting any row, i.e. you have a WHERE statamenet that does not match. The second code will not print "Update success" if no rows were affected.

    Of course, if you're sure that your WHERE statement has to match, you can use both codes without any difference and using the second one could help you to spot any potential bug, i.e. it doesn't match and so something went wrong (probably the id was different from the one you expected).

    Generally, to answer your question, mysql_num_rows is needed only if you want to know how many lines were affected. It's not mandatory at all to use it.

    So, it depends on what you want. Both are good, but they are different.