Rajubhai Rathod Rajubhai Rathod - 7 months ago 9
SQL Question

MySQL database search php issue

I have written basic script for search database of my current php site. its showing me data even if I do not write any word in search box as well it show many row same for any keyword. as well its not getting refreshed for new search. Please check and let me know what I have missed in this ?
Thanks



<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php

include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');

$q=$_POST['q'];
$q=mysql_escape_string($q);
$q_fix=str_replace(" ","%",$q); // Space replacing with %
$sql=mysql_query("SELECT qu_text FROM quotes WHERE qu_text LIKE N'%$qu_text%'");
}
?>
<html>

<body>
<form method="post" action="">
<input type="text" name="q" /> <input type="submit" value=" Search " />
</form>
<?php
while($row=mysql_fetch_array($sql))
{
$title=$row['qu_text'];
echo '<div>'.$title.'</div>';
}
?>
</body>
</html>




Answer

Your SQL is wrong.

The variable $qu_text is not initialised anywhere.

SELECT qu_text FROM quotes WHERE qu_text LIKE N'%%'

You have added wild card like on $q_text. It does not get any value, therefore, it is showing all results.

As the query is becoming:

Correct Query:

$sql=mysql_query("SELECT qu_text FROM quotes WHERE qu_text LIKE '%$q%'");