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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?