views:

56

answers:

2

i created a user defined sql query that doesn't work. users are supposed to be able to enter search strings in an input field, submit then see the results of their search but everytime i enter a search for something that i know is in the database i get the unknown column "x" in "where clause" error message.

would you please help me fix the problem? here's the code that i wrote for it...

...
mysql_select_db("mydb", $c);
$search = $_POST['search'];

$rslt = mysql_query("SELECT * FROM mytable
WHERE 'mycolumn' RLIKE $search");

while($row = mysql_fetch_array($rslt))
  {
  echo $row['myrow'];
  echo "<br />";
  }

if (!$row)
  {
  die('uh oh: ' . mysql_error());
  }

?>
+4  A: 

Change the code to this:
1) Convert quotes to backticks around column name.
2) Surround $search with single qoutes to make it a string.

 $rslt = mysql_query("SELECT * FROM mytable WHERE `mycolumn` RLIKE '{$search}'");
shamittomar
[Backticks are unnecessary unless the column name is also a reserved word in MySQL](http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html)
OMG Ponies
thank you all very much!!! :)
David Lee
@OMG Ponies, yes but we do not know whether in his code mycolumn is a reserved name or not. So, it's always safe to follow this practice.
shamittomar
A: 

I would like to add a few about security and performance.

It is unsafe to put user input (any GET, POST or cookie data) directly into the SQL query. This is a serious security issue called SQL injection. To avoid it, use mysql_real_escape_string() function.

Also, SELECT * FROM mytable ... is not a good practice. It is recommended to explicitly list all the columns needed even if they all are:

SELECT col1, col2, col3, col4, col5 FROM mytable ...
vadimbelyaev