[英]simple php search code not returning and results
我試圖讓一個簡單的PHP搜索腳本工作。 它目前從html捕獲數據並將其存儲在$ input中。 問題是我不斷從下面的腳本中得到任何結果。 但是根本沒有錯誤消息。 我知道數據庫中有完全匹配的數據,但是在沒有數據的情況下,我不斷從下面的代碼中獲取消息。 我的SQL有問題嗎?
<?php
//declaring variable
$input = $_POST['find'];
//If they did not enter a search term we give them an error
if ($input == "") {
echo "You forgot to enter a search term";
exit;
}
//open connection
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
//the sql statement
$results = $dbh->prepare("select
wp_users.ID,
wp_users.display_name,
stories.SID,
stories.story_name,
stories.category,
stories.genre
FROM stories
LEFT JOIN wp_users ON stories.ID=wp_users.ID
WHERE stories.story_name = '$input' OR stories.genre = '$input'");
$results->execute();
$row = $results->fetchAll(PDO::FETCH_ASSOC);
//giving names to the fields
$storyname = $row['story_name'];
$category = $row['category'];
$genre = $row['genre'];
//put the results on the screen
echo "<b>$storyname</b>";
echo "$categoy";
echo "$genre<br>";
//This counts the number or results – and if there wasn’t any it gives a
little message explaining that
$anymatches=$row;
if ($anymatches == 0)
{
echo "<h3>Results</h3>";
echo "<p>Sorry, your search: "" . $input . "" returned zero
results</p>";
}
?>
$results = $dbh->prepare("select
wp_users.ID,
wp_users.display_name,
news.SID,
news.story_name,
news.genre
FROM stories
LEFT JOIN wp_users ON news.ID=wp_users.ID
WHERE news.story_name = $input OR news.genre = $input");
基本上,在編寫這些查詢時,您需要將字符串括在引號中。 現在,您的查詢將包含
news.story_name=Five Cats Go Missing
你需要它
news.story_name='Five Cats Go Missing'
將其括在引號news.story_name='$input'
等等中。
首先,由於您使用的是PDO,請綁定變量。 我相信你現在很容易受到SQL注入攻擊。 第二次打開您的PDO錯誤消息,如果您沒有打開PHP錯誤消息。 @Ghost建議如何打開PDO的錯誤報告,並且可以使用<?php error_reporting(-1) ?>
進行PHP報告。
有關錯誤報告的更多詳細信息,請參閱這些鏈接:
PHP錯誤報告: http : //php.net/manual/en/function.error-reporting.php
PDO錯誤報告: http : //php.net/manual/en/pdo.errorinfo.php
我也可以檢查$results->execute();
的返回值$results->execute();
。 如果您的SQL查詢語句沒有任何問題,那么它應該返回true
,否則它將返回false
,因此您的SQL出現了問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.