insert string with single quote(‘) or double quote(“) in mysql
In developing web application, we write insert query for inserting data into database. Hence i use mysql query and PHP functions for inserting string with single quote(‘) or double quote.
let we know two useful PHP function :
1. addslashes — Quote string with slashes. Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
<?php $str = "Is your name O'reilly?"; // Outputs: Is your name O\'reilly? echo addslashes($str); ?>
2. stripslashes — Un-quote string quoted with addslashes(). Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).
<?php $str = "Is your name O\'reilly?"; // Outputs: Is your name O'reilly? echo stripslashes($str); ?>
Now come to the point…..if we insert string into database with single or double quote like this :
<?php $str = "Is your name O'reilly?"; $query = "INSERT INTO tbl (description) VALUES ( '$str')"; ?>
This will occur error.
but if we use addslashes($str) function like below and then insert into database, then no error will be occurred.
<?php $str = "Is your name O'reilly?"; $desc_str = addslashes($str); $query = "INSERT INTO tbl (description) VALUES ( '$desc_str')"; ?>
similarly we can use stripslashes($str) to print that table field value like this :
<?php echo stripslashes($str); ?>
cheers 🙂