使用PHP进行MySQL查询的条件逻辑

时间:2016-07-19 05:38:03

标签: php mysql if-statement

我正在使用PHP进行MySQL查询来检索数据。我需要有一个逻辑,如果返回的数据集为空,它会显示一条警告消息,否则它会显示结果:

$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);

5 个答案:

答案 0 :(得分:0)

将此处mysql_escape_string更改为mysqli_escape_string

$where = "";
if(isset($_POST['searchQuery']) && trim($_POST['searchQuery'])){
   $searchQuery = mysqli_escape_string($conn,$_POST['searchQuery']);
   $where =" WHERE column1 = '".$searchQuery."'";
}

$sql="SELECT * FROM db.tblname ".$where;

答案 1 :(得分:0)

这很简单:

if ($result) {
    //Your code
} else {
    echo "Error: ".mysqli_error($conn);
}

答案 2 :(得分:0)

您需要对象上的num_rows

$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

答案 3 :(得分:0)

首先查看mysqli_num_rows()。这是如何

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

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

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

if(mysqli_num_rows($result) > 0) {

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

mysqli_close($conn);

答案 4 :(得分:0)

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

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

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

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_array($result)){
        echo $row["column1"];
    }
} else {
   echo "No results found";
}

mysqli_close($conn);