0

Sometimes I need to know MySQL has found the record or no. I don't mean to know is there affected rows or not, just finding.

    $db = database_system::connect();
    $query = "UPDATE member SET username=?,password=? WHERE id=?";
    $stmt = $db->prepare($query);
    $stmt->bind_param("ssi",$this->username,$this->password,$this->id);
    $stmt->execute();
    $stmt->store_result();
    if(!$stmt->affected_rows) throw new Exception("something about");
    $stmt->close();

For example, php code above will throw exception if there is no affected record, but I wanna throw exception when there there is no such user (with that ID).

Milad Rahimi
  • 3,464
  • 3
  • 27
  • 39

2 Answers2

0

You need to check it in a separate query. The number of affected rows can return zero if the details haven't changed, too. (i.e. updating a valid user ID with the same username & password as it was before)

So best run a separate select for the user, first.

Steve Horvath
  • 508
  • 1
  • 4
  • 10
0

You can set an option to return the number of rows found, instead of the number of rows updated.

For PDO on PHP 5.3 and later:

$p = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));

For MySQLi:

mysqli_real_connect($dsn, $host, $u, $p, $dbname, $port, $socket, MYSQLI_CLIENT_FOUND_ROWS);

George
  • 934
  • 2
  • 10
  • 21