I am trying to get a simple php search script to work. It currently captures the data from an html and stores it in $input. The problem is that I keep getting no results from the script below. there are no error messages at all though. I know the database has the exact match data in it, but I keep getting the message from my code below for when there is no data. Is something wrong with my 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");
Basically, when writing these queries you need to enclose strings in quotes. Right now, your query would contain
news.story_name=Five Cats Go Missing
You need it to be
news.story_name='Five Cats Go Missing'
Enclose it in quotes news.story_name='$input'
and so on.
First and foremost, since you are using PDO, bind your variables. I believe you are vulnerable to SQL injection at the moment. Second turn on your PDO error message, and PHP error messages if you don't have them on. @Ghost suggested how to turn on your error reporting for PDO, and you can user <?php error_reporting(-1) ?>
for PHP reporting.
Refer to these links for more details on error reporting:
PHP Error Reporting: http://php.net/manual/en/function.error-reporting.php
PDO Error Reporting: http://php.net/manual/en/pdo.errorinfo.php
I also you can check the return value of the $results->execute();
. If there is nothing wrong with your SQL query statement, that should return true
, with not it will return false
, thus there is something wrong with your SQL.