0

I am trying to check if row exists. I am getting

Commands out of sync; you can't run this command

I am getting this error because I added $stmt->store_result(); if I remove that line num_rows doesn't return true. How can I check if the row exists?

$title = urldecode($_GET['product-tit/']);
$id = $_GET['item-id-pr'];
$mydb = new mysqli('localhost', 'root', '', 'database');

if(empty($title) || empty($_GET['item-id-pr'])){
header('Location: products.php');
exit();
}
else{
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $title, $id);
$stmt->execute();
$stmt->store_result();
?> 
<div>

<?php
if($stmt->num_rows < 1 )  {
     echo "not found";
     exit();


    } else{
$result = $stmt->get_result();
 echo $mydb->error;

 while ($row = $result->fetch_assoc()) {





echo wordwrap($row['price'], 15, "<br />\n", true); 
     exit();
}
$mydb->close ();}}
?>
</div>
user2666864
  • 67
  • 3
  • 7
  • 12

1 Answers1

3

It's quite a strange desire of PHP users for the number of rows. Everyone is so eager to get it, while in a web-development there are only a few, extremely rare cases when one is really need it.

Say, here we actually need some data, not number of rows. But using this number only to see if we have any data. Doesn't it look funny/redundant? If we have our data already - why would we need any extra facilities to see if we have it or not?

<?
if(empty($_GET['product-tit']) || empty($_GET['item-id-pr'])){
    header('Location: products.php');
    exit();
}

$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $_GET['product-tit'], $_GET['item-id-pr']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) { // <---- HERE it is! 
     echo "not found";
     exit();
}
?> 
<div>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345