views:

148

answers:

2

I'm currently trying to pull data from MYSQL using PHP and I keep getting the following error:

"Could not retrieve records: 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 '%PC4198% OR oem LIKE %Fluke%' at line 1 "

My SQL statement is as follows:

$sql = "SELECT * FROM account WHERE `NSC ID` LIKE %".$nscid."% OR oem LIKE %".$oem."%";

Any help is greatly appreciated.

+10  A: 

Your strings should be quoted:

$sql = "SELECT * FROM account WHERE NSC ID LIKE '%".$nscid."%' OR oem LIKE '%".$oem."%'";

That said, you should really consider using PDO or an ORM.

Edit:

The main point of using PDO is, as Bill said, to prevent SQL injection (caused by concatenating possibly dirty strings into SQL).

The same query, in PDO style, would be:

$query = $connection->prepare('SELECT * FROM account WHERE NSCID LIKE :nscid OR oem LIKE :orm');
$query->bindValue(':nscid', '%'.$nscid.'%', PDO::PARAM_STR);
$query->bindValue(':oem', '%'.$oem.'%', PDO::PARAM_STR);

It's some more code, but it'll protect you from most (all?) SQL injections, by letting the library do the escaping.

(The parameter types for bindValue are optional, but good practice.)

Tordek
+1 for last helpful sentence
alex
It would be helpful to explain how those interfaces would help in Josh's case. His error was simply a failure to delimit a string literal in quotes. You may be anticipating SQL injection problems due to his interpolation of PHP variables into the SQL string, but it's not clear from your answer.
Bill Karwin
Thanks to both of you! That worked!!!
+1  A: 

even better yet, the operators { and } can allow you to do this

$sql="SELECT * FROM account WHERE NSC ID Like '%{$nscid}%' OR oem LIKE '%{$oem}%'";

you dont need the {} if its a single var like that but if you use an object you do need them:

$hi_example="yarg i am a {$person->type}";
strubester
Thanks to both of you! That worked!!!