Fahid Posted April 2, 2008 Share Posted April 2, 2008 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. Link to comment https://forums.phpfreaks.com/topic/99099-escaping-strings-for-using-in-mysql-queries/ Share on other sites More sharing options...
Fahid Posted April 2, 2008 Author Share Posted April 2, 2008 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()); ?> Link to comment https://forums.phpfreaks.com/topic/99099-escaping-strings-for-using-in-mysql-queries/#findComment-507070 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.