Jump to content

Escaping Strings for using in MySQL Queries


Fahid

Recommended Posts

I created a simple PHP/MySQL GUESTBOOK Script, when user add a SINGLE QUOTE ' in any field, MySQL can't add it to database, I understand that we have to escape (use \ ) in such cases. but can't remember how exactly we should do it, code part-4 shows how I somehow have managed to avoid the error, but I know this is not the most efficient way in the world.

 

Example-1: I have to add a couple of fields to database

<?php

$Name = $_POST['Name'];
$Phone = $_POST['Phone '];
$query = "INSERT INTO `tablename` VALUES ('$Name', '$Phone' );";
$result = mysql_query($query) or die(mysql_error());

?>

in above case if some one adds his name as Myname's Name MySQL will return an error. And that's what I am talking/Asking about.

 

 

Example-2: I somehow managed to work it out, but am not satisfied with it

<?php

$Name = str_replace("'","\'",str_replace("\'","\\'",$_POST['Name']));
$Phone = str_replace("'","\'",str_replace("\'","\\'",$_POST['Phone ']));
$query = "INSERT INTO `tablename` VALUES ('$Name', '$Phone' );";
$result = mysql_query($query) or die(mysql_error());

?>

Example-2 will not make any problem for MySQL, but I am not satisfied with it, moreover it is expected that this way I can alter the user's submitted data a little.

 

 

Please help.

I think I have got the solution while visiting this forum, please confirm if you see it.

 

Even if this function is the one I am looking for, still the question is:

In which PHP Versions this function is supported?

 

<?php

$Name =  mysql_real_escape_string($_POST['Name']);
$Phone = mysql_real_escape_string($_POST['Phone ']);
$query = "INSERT INTO `tablename` VALUES ('$Name', '$Phone' );";
$result = mysql_query($query) or die(mysql_error());

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.