I have a search field feature on my website, with below PHP code:
if(isset($_GET['search_ti']) && $_GET['search_ti'] != "")
{
$search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']);
$sqlCommand = "
SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%'
";
$result = $mysqli->query($sqlCommand) or die(mysql_error());
...
The URL variable search_ti
is the keyword for the search, which I got from the URL. For example:
searchResult.php?search_ti=home
If the keyword is found in my MySQL table, the result shows and no errors.
But if the keyword is not found, the web browser generates below error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1
What is wrong with my code?
ADDITIONAL INFO:
The complete PHP code: http://jsfiddle.net/eQSZc/
The keyword: home. The error only shows if the keyword is not found in my table.
Change your pagination_mechanism_and_buttons_variables_for_Search.php
to the one in http://jsfiddle.net/GsNmw/1/
I have added the following block just before you construct the $limit
and change the $limit
as well.
$start = ($pn - 1) * $itemsPerPage;
if($start<0){
$start = 0;
}
$limit = 'LIMIT ' .$start .',' .$itemsPerPage;
This avoids negative limit and hence avoids your error.
Another alternative for this is to use PDO
.
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$keyword = '%' . search_ti . '%';
$stmt = $dbh->prepare("SELECT *
FROM page
WHERE title LIKE ? OR
body LIKE ?");
$stmt->bindParam(1, $name);
if ($stmt->execute())
{
while ($row = $stmt->fetch())
{
print_r($row);
}
}
?>
This will allow you to select records with single quotes.