I am trying to make a live search box for a library using ajax, mysql and php. I have implemented the search for the books. ie when you type in the title of the book, it shows the suggestions. However, I am trying to implement it also for the authors column in my database such that when you type in a name of an author, it shows the books that the author has written from the database but I don't seem to be getting the mysql statement on line 4 correctly. please help.
<?php
include('config.php');
$s1=$_REQUEST["n"];
$sql="SELECT * from books where (Title like '%".$s1."%') OR (Author like '%'.s1.'%')";
$result=mysqli_query($conn,$sql);
$s="";
<?php
include('config.php');
$s1=$_REQUEST["n"];
$sql="SELECT * from books where `Title` like '%".$s1."%' OR `Author` like '%".$s1."%')";
$result=mysqli_query($conn,$sql);
You have some misplaced quotes as well as missing $
in your query code line. So You need to change
Author like '%'.s1.'%'
To:-
Author like '%".$s1."%'
Note:- Your Query is wide-open for SQL INJECTION
.So try to use prepared statements
Reference:-
Personally I dont like OR's. Instead I prefer Union. Hey I get paid by the hour (actually I get salary) But I still like to over complicate things.
<?php
include('config.php');
$s1=$_REQUEST["n"];
$sql="
SELECT
b.*
FROM
books AS b
JOIN
(
SELECT
id
FROM
books
WHERE
Title like ?'
UNION
SELECT
id
FROM
books
WHERE
Author like ?
) AS v
ON b.id = v.id
";
$stmt = mysqli_prepare($conn,$sql);
$stmt->bind_param("ss", '%'.$si.'%', '%'.$si.'%');
$stmt->execute();
$stmt->store_result();
$resultrow = array();
$stmt->bind_assoc($stmt, $resultrow);
while($stmt->fetch())
{
print_r($resultrow);
}
No actually the performance is better, OR's are crap for performance. And if you do it in a sub query with just the ID, then the tempory table you create by doing the union is tiny and then join and pull just what you want, sort etc... And it should be a few times faster, if you have like a couple million records.
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.