我找不到显示"No Results."的方法



只要在搜索框中输入数据库中的名称,下面的代码就可以正常工作。如果输入的名称不在数据库中,则会出现错误"警告:为foreach((提供的参数无效……"…。。在第201行。'我希望显示类似"无结果"的内容,而不是这个一般性错误。有什么建议吗?我知道以前有人问过这个问题,但似乎没有一个答案与我在这里使用的输出类型相匹配。

enter code here
<?php 
include 'connect.php';
if (isset($_POST['submit-keyword'])) {
$keyword = $_POST['keyword'];
}  
try {
//first pass just gets the column names
print "<table>";
$result = $con->query("SELECT * FROM Bath_Wells_NBR WHERE Founder LIKE '%$keyword%' ORDER BY DATE");
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} 
// end foreach
print " </tr>";

//second query gets the data
$data = $con->query("SELECT * FROM Bath_Wells_NBR WHERE Founder LIKE '%$keyword%' ORDER BY DATE");
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try

?>

您需要做的第一件事是使用PDO对象,并实际使用准备好的语句来避免sql注入,如下所示:

$keyword = '%' . $keyword . '%';
$q = $con->prepare("SELECT * FROM Bath_Wells_NBR WHERE Founder LIKE :keyword ORDER BY DATE");
$q->bindParam(':keyword',$keyword,PDO::PARAM_STR);
$q->execute();
//here we will use fetchAll to get the full dataset of results, or an empty array
$result = $q->fetchAll();

现在你有了$result,它是你的数据的数组,或者是空的,所以你可以通过说:来解决你的问题

if(count($result) < 1) {
//output an error message
} else {
//output your table
}

现在您有了解决方案,让我们稍微简化一下代码。记住,程序员需要DRY代码,所以我们不想做两次相同的查询。让我们假设我们的结果计数大于0,所以我们在else块内。

{
//get all the array keys from the first entry in the result.  These are the column names from the database which we want to use for our headings
$headings = array_keys($result[0]);
//now we want to do the same thing to each element, i.e. wrap it in html tags so let's make use of array_walk.  We use the & symbol to pass the values by reference so we can amend them
array_walk($headings, function(&$field, &$key) {
$field = <th>$field</th>
});
//so now we have an array of table headings, so lets quickly implode them, we don't want to write a whole loop for this
echo <tr> . implode('',$headings) . </tr>;

现在,您可以进行原始循环,只需输出值,嘿,presto,更简单的代码!您也可以尝试使用array_walk_recursive进行实验,看看是否可以对嵌套循环的值执行同样的操作,毕竟您只想将它们封装在<td>标记中!

注意,我还没有测试过这个,所以代码,但你应该能够使用它,只是有一点发挥和实验它

快乐的编码!

最新更新