如何在表格中找不到匹配项时显示MySQL结果

时间:2016-06-23 15:24:32

标签: php mysqli

这个问题似乎已被多次提出,但没有一个答案对我有用。没有计算数量或行数,没有。

我编写了以下查询函数,以便用户从下拉列表中选择技能并必须输入城市的表单进行访问。当技能和城市匹配时,结果会正确显示。这是代码:

function search() {
    $city=$_POST['city'];
    if(!isset($_POST['city'])) echo "You must enter a city to find a match.";

    $sql = "SELECT skill.skill_name, team.city FROM skill INNER JOIN team ON skill.skill_id=team.skill WHERE skill.skill_name LIKE '$skill' AND city LIKE '$city' ";
    foreach ($myconnect->query($sql) as $row) {
      if($sql) {
          echo $skill . " is available in " . $row['city'];
      }
      else {
         if(!$sql)
            echo "No result found.";
         }
      }
  }//submit
}

你能直接帮我解决吗?

谢谢。

澄清:当找到匹配时,代码正确显示信息。但是当没有匹配时,它不会显示没有找到结果的消息。

@Your Common Sense的解决方案稍作修改:(1)发布var $ _POST ['技能']到$ _POST ['技能']并回应表格的后期变种而不是$行的结果。

$sql = "SELECT s.skill_name, t.city FROM skill s JOIN team t ON s.skill_id=t.skill 
        WHERE s.skill_name = ? AND city = ?";
$stmt = $myconnect->prepare($sql);
$stmt->bind_param("ss", $_POST['skill'], $_POST['city']);
$stmt->execute();
$data = $stmt->get_result()->fetch_all();
if (!$data) {
    echo "No result found.";
} else {
    foreach ($data as $row) {
        echo htmlspecialchars($_POST['skills']) . " is available in " . htmlspecialchars($_POST['city']);
    }
}

1 个答案:

答案 0 :(得分:2)

周围有太多错误的答案,所以值得写一个合适的答案。

$sql = "SELECT s.skill_name, t.city FROM skill s JOIN team t ON s.skill_id=t.skill 
        WHERE s.skill_name = ? AND city = ?";
$stmt = $myconnect->prepare($sql);
$stmt->bind_param("ss", $_POST['skill'], $_POST['city']);
$stmt->execute();
$data = $stmt->get_result()->fetch_all();
if (!$data) {
    echo "No result found.";
} else {
    foreach ($data as $row) {
        echo htmlspecialchars($row['skill_name']) . " is available in " . htmlspecialchars($row['city']);
    }
}