When an SQL query is built as a string, every value that comes from outside the application must be escaped before it is concatenated. The mysqli_real_escape_string function handles the escaping, but it returns the value without quotes, so they still have to be written by hand. Since PHP 8.6 the mysqli_quote_string function can be used, which escapes the string and wraps it in single quotes in one step.
Let's say a users table contains a name with an apostrophe:
| id | name |
|---|---|
| 1 | John |
| 2 | O'Reilly |
| 3 | Bob |
The following example looks up that row using mysqli_real_escape_string:
<?php
$mysqli = mysqli_connect('127.0.0.1', 'root', 'passwd123', 'testdb');
$name = "O'Reilly";
$query = 'SELECT * FROM users WHERE name = '.mysqli_real_escape_string($mysqli, $name);
echo $query.PHP_EOL;
$result = mysqli_query($mysqli, $query);
print_r(mysqli_fetch_assoc($result));
Output:
SELECT * FROM users WHERE name = O\'Reilly
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax
The apostrophe is escaped, but nothing marks the value as a string, so the database server reads O\'Reilly as part of the query itself and reports a syntax error. Adding the quotes manually solves it, but they are easy to forget, and the mistake only shows up once a value actually contains a quote.
The mysqli_quote_string function returns the value with the quotes already attached:
<?php
$mysqli = mysqli_connect('127.0.0.1', 'root', 'passwd123', 'testdb');
$name = "O'Reilly";
$query = 'SELECT * FROM users WHERE name = '.mysqli_quote_string($mysqli, $name);
echo $query.PHP_EOL;
$result = mysqli_query($mysqli, $query);
print_r(mysqli_fetch_assoc($result));
Output:
SELECT * FROM users WHERE name = 'O\'Reilly'
Array
(
[id] => 2
[name] => O'Reilly
)
The query is now valid and returns the matching row. The same is available as the mysqli::quote_string method.
The mysqli_quote_string function is not a replacement for prepared statements. A prepared statement keeps the value out of the query text, so it is still the safer choice. The new function helps when a query has to be built as a string.
Leave a Comment
Cancel reply