View Full Version : Can't get mysql_real_escape_string() to work

01-07-2010, 10:54 PM
Evening everyone,

To save the hassle of manually publishing content to my site (download file, edit, save, upload)...I have wrote a small PHP/MySQL script that will do it for me. Quite simply, I enter stuff into the form, it's stored in the database and my website displays it.

I'm a novice at PHP and ran into the problem of using punctuation in my site content. I'm looking to use apostrophes and quotation marks, although I get the following error when I try to do so:

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 's punctuation','','')' at line 2

Fair enough, from learning the most basic PHP a few months ago I'd remembered you have to put a backslash before a punctuation mark. So I did some Google searching and learned about mysql_real_escape_string() .

So I've been looking where to implement it in my code, and just can't figure it out. My form action="entry.php"


$con = mysql_connect("localhost","root","");
if (!$con)
die('Could not connect: ' . mysql_error());

mysql_select_db("database1", $con);

$sql="INSERT INTO news (image_name, title, description, read_more_link, article_body)
VALUES ('$_POST[image_name]','$_POST[title]','$_POST[description]','$_POST[read_more_link]','$_POST[article_body]')";

if (!mysql_query($sql,$con))
die('Error: ' . mysql_error());
echo "1 News Record Added /";

// Where the file is going to be placed
$target_path = "images/news/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "1 Image ( ". basename( $_FILES['uploadedfile']['name']).
" ) has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";


Would really appreciate any pointers. Thanks :thumbsup:

01-07-2010, 11:13 PM
Have you read the manual? There are examples on how to use it.


01-08-2010, 02:55 AM
You should consider using my mressf function. replace this line

$sql="INSERT INTO news (image_name, title, description, read_more_link, article_body)
VALUES ('$_POST[image_name]','$_POST[title]','$_POST[description]','$_POST[read_more_link]','$_POST[article_body]')";

$sql=mressf("INSERT INTO news (image_name, title, description, read_more_link, article_body)
VALUES ('%s','%s','%s','%s','%s')", $_POST['image_name'], $_POST['title'], $_POST['description'], $_POST['read_more_link'], $_POST['article_body']);
and copy and paste the mressf function (http://www.jaygilford.com/php/sprintf-and-mysql_real_escape_string-all-in-one-function/) from my website to somewhere in your script