In PHP, mysqli_escape_string() escapes special characters in a string for use in a SQL statement on that connection; it is an alias of mysqli_real_escape_string().
Object-oriented style uses $mysqli->real_escape_string($string) (there is no separate escape_string method name in common use). Escaping depends on the connection character set, so call set_charset() first. Prefer prepared statements instead of building SQL with escaped strings.
Syntax
Call mysqli_escape_string() with the values you need. Start with this line.
PHP
$safe = mysqli_escape_string($mysqli, $value);
Call
What it does
mysqli_escape_string($mysqli, "O'Reilly")
Escapes the quote for safe inclusion in SQL.
mysqli_real_escape_string($mysqli, $value)
The canonical function name; escape_string is an alias.
$mysqli->real_escape_string($value)
Object-oriented escaping method.
mysqli_escape_string() and mysqli_real_escape_string() are the same. Escaping is not enough if you forget quotes around values, and it is easy to misuse. Prepared statements with bind parameters are the safer default.
Safer pattern: bind the value instead of escaping into SQL text.
PHP
<?php
$mysqli = mysqli_connect("localhost", "demo", "secret", "shop");
mysqli_set_charset($mysqli, "utf8mb4");
$name = "O'Reilly";
$stmt = mysqli_prepare($mysqli, "SELECT id FROM products WHERE name = ?");
mysqli_stmt_bind_param($stmt, "s", $name);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id);
mysqli_stmt_fetch($stmt);
echo "id=", $id, PHP_EOL;
mysqli_stmt_close($stmt);
mysqli_close($mysqli);
Output
id=7
How It Works
A placeholder ? stands in for the name value.
bind_param sends the string safely without manual escaping.
execute + fetch reads the demo row.
Sample output when connected to a demo database shows id=7.
Frequently Asked Questions
Yes. mysqli_escape_string() is an alias of mysqli_real_escape_string(). Prefer the real_escape_string name in new code, or better, use prepared statements.
Escaping rules depend on the connection character set. Call set_charset('utf8mb4') before escaping so multi-byte characters are handled correctly.
It helps only when you correctly place the escaped value inside quotes. Prepared statements are safer and clearer, so prefer them.
Use $mysqli->real_escape_string($string). That is the method form of the real_escape_string / escape_string function pair.
Learn prepared statements (or execute_query with parameters) first. Treat escaping as a legacy technique you may see in older code.