0

I need to implement a search in mysql table for a certain word to find in a specific column (type: text).

I thought that the easiest way is to do:

$str = "something"; # let's say passed by POST or GET from a form
$sql = "select lala, textThing from table_name where dudu=1 and textThing LIKE %'$str'%";

This seems to work just fine if doing query manually in mysql, but not on php through web. It throws

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 '%searchedString%' at line 1

where searchedString is, well, you know, the string I searched for :)

First PHP looks like this:

$str = NULL;


echo "<p>Search for a string</p>";
echo "<form name='formSearch' action='result.php' method='post'>";
echo "<input type='text' name='text' size='30'/>";
echo "<input type='submit' name='search' value='Search'/>";
echo "</form>";

The second one is just getting the "text" and doing mysql and supposed to show the data

trainoasis
  • 6,419
  • 12
  • 51
  • 82

2 Answers2

2

You have to put your LIKE clause between quotes. Escape them in your php code like this :

$sql = "select lala, textThing from table_name where dudu=1 and textThing LIKE \"%".$str."%\""
BMN
  • 8,253
  • 14
  • 48
  • 80
1

You need to include the % inside a quote or double quote.

$sql = "select lala, textThing from table_name where dudu=1 and textThing LIKE '%$str%'";

or

$sql = "select lala, textThing from table_name where dudu=1 and textThing LIKE '%" + $str + "%'";

lorraine batol
  • 6,001
  • 16
  • 55
  • 114