rwetyeutymj rwetyeutymj - 4 months ago 23
PHP Question

Conditional Logic on MySQL Query with PHP

I am doinga MySQL query to retreive data using PHP. I need to have a logic that if the data set returned is empty it shows a warning message else it displays the results:

$searchQuery = mysql_escape_string($_POST['searchQuery']);

$sql="SELECT * FROM db.tblname WHERE column1 = '".$searchQuery."'";

$result = mysqli_query($conn,$sql);

while($row = mysqli_fetch_array($result)){
echo $row["column1"];
}

mysqli_close($conn);

Answer

You need num_rows on the object

$result = mysqli_query($conn,$sql);
if ($result->num_rows == 0) { 
  echo 'result empty';
} else {
  while($row = mysqli_fetch_array($result)){
     echo $row["column1"];
  }
}

http://php.net/manual/en/mysqli-result.num-rows.php