rowCount(), Why doesnt it work on create user ? Any options?

67 views Asked by At

Creating new user in mysql as :

$query = $dbconnection->prepare("CREATE USER 'john'@'localhost' IDENTIFIED BY 'mypass'");
$query->execute();
$counts = $query->rowCount();
return $counts;

Generally in other queries, I use rowCount() to check whether the query got successful or not. if rowCount() >1, query successful. But I realised this doesnt work in creating user.
In this case, user is created, but rowCount() still results the value 0. Is there any way, to check whether this query is successful.

UPDATE in @GHOST comment: This query returns the value 1, to confirm that data is inserted, or a row is affected.

     $query = $this->link->prepare("INSERT INTO agent(uname,password,) VALUES(?,?");    
    $values = array($uname,$pw);
    $query->execute($values);
    $counts=$query->rowCount();
    return $counts;

I am looking for some way, to check in same way for the previous case.

2

There are 2 answers

5
Colin Schoen On BEST ANSWER

Thanks for the additional code

$query->execute(); This will return True on a successful query and False if there was an error when executing the query

if !($query->execute() {
    echo "Ouch, there was an error.";
}
1
Devon Bessemer On

Colin's answer is correct for the standard PDO error mode.

This is more of a long comment than an answer but it is important to make note of the differences of return values for rowCount() and execute() especially for updates and deletes.

When you update and delete, you can have a rowCount() of 0 but an execute() of true. This means that the query succeeded but no rows matched the constraints provided (usually WHERE).

Therefore, when performing updates and deletes, you should be checking both return values. One to make sure the query succeeded and one to check to see if rows were affected. Checking for both will make debugging easier and prevent a fatal error on rowCount() if the query fails.