开发者

Unknown column 'xyz' in 'where clause'

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 so far...

...
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());
  }

?>


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}'");


This helps for sure just change the variable $search to be read as a string i.e $search so it will be like this

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


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 ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜