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>
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!