douwen5833 2015-10-18 17:06
浏览 44
已采纳

PDO语句错误php mysql [重复]

This question already has an answer here:

i am trying to fetch product list from mysql table. I am trying the following code but it is not working. Any suggestions please.

Fatal error: Call to undefined method mysqli_stmt::rowCount()

Code

$query = "SELECT id, name, price FROM female_products ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$num = $stmt->rowCount();
if($num>0)
{
//my work here
}

Config.php

 $db_username = 'root';
$db_password = '';
$db_name = 'ecommerce';
$db_host = 'localhost';

try {
$con  = new mysqli($db_host, $db_username, $db_password,$db_name);

 }catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
 }
</div>
  • 写回答

1条回答 默认 最新

  • dsqpx86002 2015-10-18 17:46
    关注

    Assuming you want a real PDO solution, rather then a mysqli one:

        try {
        $aOptions = array(  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
        // play around with options
    
        $dbh = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME.';charset=utf8', ''.DBUSER.'', ''.DBPWD.'',$aOptions); 
    }
    catch(PDOException $e) {
        echo $e->getMessage(); 
        // do something smarter then just echo error!
    }
    
    
    $sql = "SELECT id, name, price FROM female_products ORDER BY name";
    $stmt = $dbh->query($sql);
    $aArray = $stmt->fetchAll();
    
    if(count($aArray) > 0){
        // do something
    }
    else{
       // empty result 
    }
    

    I personally think PDO is a much easier style then mysqli. Options: you certainly gonna play with it soon, so it is handy to use an array for it. You have used prepare,but yo do not make use of a prepared statement yet?? If this code works, try to find out hoe prepared statements work: one of the best defenses against SQL attacks!!

    For configuration i used constants, so you need to define theme in your config. Constants, because they will never change during execution of your script!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办