简体   繁体   中英

LIKE MySQL Prepared Statement

I am creating a search engine with AJAX and a prepared statement. The search variables are sent and the AJAX query is successful, but the problem lies with my search query syntax. No matter how exact my search term is to my keywords, my num_rows is always 0. I am adding % % to search terms, I have tried deleting white space but I am out of ideas.

Examples of keywords are sad, acoustic, electric, blues etc.

<?php
include 'config.php';

$partialSearch = "%".$_POST['partialSearch']."%";

$stmt = $mysqli->prepare("SELECT Name FROM videos WHERE Keywords LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($Name);

if($stmt->num_rows() == 0)
{
echo "No results found for ".$_POST['partialSearch'];
}else{
echo "Results for ".$_POST['partialSearch'];
echo $Name;
}
?>
if($stmt->num_rows() == 0)

This is incorrect. num_rows is a property, not a method. It should have been:

if($stmt->num_rows == 0)

I'd suggest enabling error reporting to discover silly errors like this. See this thread for more information on how to do that.

You should add a call to store_result to get accurate count of records in the results:

Try:

...
$stmt->execute();
$stmt->store_result(); // Add this line
$stmt->bind_result($Name);

if($stmt->num_rows == 0)
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM