2010-09-16 27 views
1

在過去的結果我會做一些像這樣:如何檢查是否有預處理語句

$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) { 

今天我做同樣的事情,但是有準備的語句:

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

的如果($ stmt ...是「如果此查詢得到結果」,或者是「如果該查詢被執行而不管結果與否,即如果它執行沒有錯誤」,那麼它的第二行如果($ stmt ...)

什麼我在試着g要解決的是準備好的語句你怎麼做mysql_num_rows()== FALSE?

謝謝!

回答

6

您可以使用PDOStatementrowCount()方法獲取的行數返回:

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

或者,如果rowCount()被證明是不可靠的,你可以這樣做:

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

'rowCount時()'是一個方法,並正式支持它只是在操作受影響的行,但是,是爲MySQL這個工程作爲行的一個結果數量。 – Wrikken 2010-09-16 00:50:41

+2

+1但請注意,'rowCount()'僅適用於使用緩衝查詢的情況。沒有接口可以告訴你在獲取結果集之前結果集中有多少行。 – 2010-09-16 00:51:29

+0

@Wrikken,謝謝,更新。 – 2010-09-16 00:51:37

1

PDOStatement::rowCount()回報由DELETE,INSERT或UPDATE語句影響的行數,而不是選擇查詢返回的行數, 用於我使用的選擇查詢:
fetchAll(PDO::FETCH_OBJ);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); 
?>