简体   繁体   中英

How to check if there are results with Prepared Statements

In the past I would do something like so:

  $sql = 'SELECT * FROM customers WHERE customer_email="' . mysql_real_escape_string($_POST['customer_email']) . '" ';
  $res = mysql_query($sql);

  // if there are no hits...
  if(mysql_num_rows($res) == FALSE) {

Today I am doing the same thing however with prepared statements:

  $stmt = $dbh->prepare("SELECT * FROM customers where customer_email = ? LIMIT 1");
  if ($stmt->execute(array($_POST['customer_email']))) {

The 2nd line of my prepared statement if($stmt... is that "if this query gets a result" or is it "if this query is executed regardless of results or not ie if it executes without error".

What I'm trying to work out is with prepared statements how do you do the equivalent of mysql_num_rows() == FALSE?

Thanks!!

You can use the rowCount() method of PDOStatement to get the number of rows returned:

$stmt = $dbh->prepare("SELECT * FROM customers where customer_email = ? LIMIT 1");
$stmt->execute(array($_POST['customer_email']));
if($stmt->rowCount() > 0) {
   //fetch stuff...
}

Or, if rowCount() proves to be unreliable, you can do this:

$all = $stmt->fetchAll();
if(count($all)) {
   //loop through the set...
}

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement and not the number of rows returned by select query, for select query I use :
fetchAll(PDO::FETCH_OBJ); And echo count($lignes);

<?php
$PARAM_hote='localhost'; 
$PARAM_port='3306';
$PARAM_db='test'; 
$PARAM_user='root'; 
$PARAM_pwd=''; 
try
{
$connexion = new PDO('mysql:host='.$PARAM_hote.';dbname='.$PARAM_db, $PARAM_user,$PARAM_pwd);
}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
$requete_prepare_1=$connexion->prepare("SELECT * FROM `test_mysql`"); 
$requete_prepare_1->execute();
$lignes=$requete_prepare_1->fetchAll(PDO::FETCH_OBJ);
echo count($lignes); 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM