Reputation: 753
I am building a search into my site where the search term is stored in a database.
Here is my code
<?php
$search = $_GET["q"];
if ($search <= "") {
}
else {
$con = mysql_connect("localhost", "cl49-XXX", "XXX");
if (!$con) {
die('Could not connect: line 513 ' . mysql_error());
}
mysql_select_db("cl49-XXX", $con) or die("Unable to select database");
$result = mysql_query("SELECT * FROM registrations WHERE 'rname' LIKE '%$search%'") or die('Error: Line 519 (' . mysql_error() . ')');
$num_rows = mysql_num_rows($result);
if ($num_rows=="0"){
echo"<h4> No Results Found for <b>$search</b>. Please try a different search</h3>";
}
else {
echo "<h3>$num_rows results found for <b> $search</b></h3><br /><br />";
}
If I search the name "donna" (this name is in the DB) I get the error
Unknown column 'donna' in 'where clause'
Upvotes: 0
Views: 1606
Reputation: 44844
Change
mysql_query("SELECT * FROM registrations WHERE 'rname' LIKE '%$search%'")
to
mysql_query("SELECT * FROM `registrations` WHERE `rname` LIKE '%".$search."%'")
Upvotes: 1
Reputation: 287
There is a difference between ` and '. You have used ' in this post for both the column name rname and '%$search%'. I guess you actually used `%$search%` in your code.
Change your code as below.
$result = mysql_query("SELECT * FROM registrations WHERE `rname` LIKE '%$search%'") or die('Error: Line 519 (' . mysql_error() . ')');
Upvotes: 0
Reputation: 1496
As all community say: don't use mysql_ functions, try mysqli or PDO, please.
Advice: escape the input, prevent injections, etc.
Do: $search = mysql_real_escape_string( $_GET["q"] );
And change this line
$result = mysql_query("SELECT * FROM registrations WHERE `rname` LIKE '%". $search ."%'") or die('Error: Line 519 (' . mysql_error() . ')');
Edit (script improvements).
mysql_num_rows returns an integer value, so, why you're comparing it with string ?
$num_rows = mysql_num_rows($result);
if (!$num_rows){
Or if ($num_rows == 0)
...
Upvotes: 4
Reputation: 6832
Assuming the column name in you table is rname
:
WHERE 'rname' LIKE
Should be
WHERE rname LIKE
Upvotes: 0