I’m having a problem when I try to insert an array that has a reserved word on it.
It’s really wierd I might say, take a look:
$sql="INSERT INTO sites (cat_id, cat_title, cat_parent, title, image, site_name, description) VALUES ('$_POST[cat_id]','$_POST[cat_title]','$_POST[cat_parent]','$title','$image','$site_name','$description')";
The array is comming from a opengraph fetch that I created but it’s not important, the question is that sometimes when the array $title, for example, or $image has a reserved word like “use” on it, the sql return the error “Error: You have an error in your SQL syntax; check the manual that corresponds….”
so that’s the case:
when the array $title = http://techcrunch.com/2012/08/28/flipboard-hits-20-million-users-3-billion-flips-per-month/ <—- it don’t work and I receive the error above.
when the array is $title = http://techcrunch.com/2012/08/27/google-nexus-7-is-now-available-in-france-germany-and-spain/ <—- it works fine!
so I think that probably because theres a ‘reserved word’ in the array $title sometimes (or any other array that I’m using) that is returning the error… So theres any way that I could protect my arrays from this error?
Thanks! 🙂
EDIT:
SOLUTION
Ok! I followed the @dystroy and @tadman advice and used PDO instead of the regular mysql connection… I don’t know if I’m totally secure against SQL injetion or attacks but it solve my problem with the reserved words. Now I can insert whatever content I have in an $array to the database.
If someone end up here with the same problem, that’s what I did (please complain if you guys find any awkwardness):
$dbh = new PDO("mysql:host=MYHOST;dbname=MYDATABASE", "USER", "PASS");
$query = "INSERT INTO sites (cat_id, cat_title, cat_parent, title, image, site_name, description) VALUES (:cat_idpost, :cat_titlepost, :cat_parentpost, :titlepost, :imagepost, :site_namepost, :descriptionpost)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':cat_idpost', $cat_id);
$stmt->bindParam(':cat_titlepost', $cat_title);
$stmt->bindParam(':cat_parentpost', $cat_parent);
$stmt->bindParam(':titlepost', $titlepost);
$stmt->bindParam(':imagepost', $imagepost);
$stmt->bindParam(':site_namepost', $site_namepost);
$stmt->bindParam(':descriptionpost', $descriptionpost);
$cat_id = $_POST['cat_id'];
$cat_title = $_POST['cat_title'];
$cat_parent = $_POST['cat_parent'];
$titlepost = $title;
$imagepost = $image;
$site_namepost = $site_name;
$descriptionpost = $description;
$stmt->execute();
Thank you guys! 😀
Always use prepared statement to insert strings in a database. Never simply concatenate them.
The problem isn’t only reserverd words but all kind of errors (or attacks) due to special values or characters. Don’t try to escape all this yourself : The database will handle that for you if you use a prepared statement.
Look at those samples based on today’s recommended library for PHP/MySQL (PDO) : http://www.php.net/manual/en/pdo.prepared-statements.php