SQL statement problem with PHP
I am currently trying to fetch data from MYSQL using PHP and I keep getting the following error:
"Failed to get records: you have an error in your SQL syntax, check the manual that matches your MySQL server version for the correct syntax used next to '% PC4198% OR oem LIKE% Fluke%' on line 1"
My SQL statement looks like this:
$sql = "SELECT * FROM account WHERE `NSC ID` LIKE %".$nscid."% OR oem LIKE %".$oem."%";
Any help is greatly appreciated.
Your lines should be quoted:
$sql = "SELECT * FROM account WHERE NSC ID LIKE '%".$nscid."%' OR oem LIKE '%".$oem."%'";
However, you should really use PDO or ORM.
Edit:
The main point of using PDO is, as Bill said, to prevent SQL injection (caused by the concatenation of possibly dirty strings in SQL).
The same PDO style query would look like this:
$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);
This is another code, but it will protect you from most (all?) SQL injection by giving the library an escaping capability.
(The parameter types for bindValue are optional, but good practice.)
a source to share