2015-06-02 62 views
5

我正在学习使用MySQL的OOP PHP。我想运行一个查询,应该打印返回的行数。我的PHP代码如下:计算OOP中的返回行数PHP

$con= mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error()); 
$email="[email protected]"; 
if($r=$con->prepare("SELECT * FROM user WHERE email=? ")){ 
$r->bind_param("s",$email); 
    if(!$r->execute()){ 
     echo mysqli_errno($con); 
    } 
    else{ 
     $rowCount=$r->num_rows; 
     echo $rowCount; 
    } 
} 

在我的数据库,邮件是在4行,所以它应该打印4,但它显示0

请告诉我错我的代码?

回答

3

您必须store result

$r->store_result(); 

而且也之前您检查行计数。请参阅手册页

被告知请人谁有时会错过阅读此功能这一重要的手动输入在这样一个字条:

如果你不使用mysqli_stmt_store_result(),和immediatley调用这个函数在执行准备语句之后,此函数通常会返回0,因为无法知道结果集中有多少行,因为结果集尚未保存在内存中。

提示

既然你是学OOP PHP与MySQL,一定要注意,到MySQL创建的连接是程序风格的语法是很重要的。而在PHP中,你可能会逃避,但在许多其他语言中你不会。为什么不把它转换成OOP语法呢?

$con= new mysqli('localhost', 'my_user', 'my_password', 'my_db'); 
+0

哦,我不知道。 – partho

0

您需要使用store_result()存储结果。了解更多here

所以,你的代码应该是这样的:

<?php 
$con= mysqli_connect('localhost','root','','dealinte_cms') or die(mysqli_error()); 
$email="[email protected]"; 
if($r=$con->prepare("SELECT * FROM user WHERE email=? ")){ 
$r->bind_param("s",$email); 
    if(!$r->execute()){ 
     echo mysqli_errno($con); 
    } 
    else{ 
     $r->store_result(); 
     $rowCount=$r->num_rows; 
     echo $rowCount; 
    } 
} 
?>