Home >Database >Mysql Tutorial >Do Prepared Statements Need `mysql_real_escape_string()` for Security?

Do Prepared Statements Need `mysql_real_escape_string()` for Security?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 23:50:29284browse

Do Prepared Statements Need `mysql_real_escape_string()` for Security?

Using mysql_real_escape_string with Prepared Statements

Question:

Is it necessary to use the mysql_real_escape_string() function when utilizing prepared statements for database queries?

Context:

The provided code demonstrates a prepared statement query using the mysqli library. However, it currently uses the mysql_real_escape_string() function to sanitize the user input.

<code class="php">$consulta = $_REQUEST["term"]."%";

($sql = $db->prepare('select location from location_job where location like ?'));

$sql->bind_param('s', $consulta);
$sql->execute();</code>

Answer:

No, prepared statements provide inherent protection against SQL injection and data manipulation when used properly. They automatically sanitize input, making mysql_real_escape_string() redundant.

Improvement:

While the query is using prepared statements correctly, a minor modification can improve its efficiency. Instead of using the bind_param() method, the execute() method can be used to pass parameters directly.

<code class="php">$sql->execute([$consulta]);</code>

Additional Note:

Although prepared statements protect against SQL injection, they do not ensure the safety of data when outputting it to the page. To prevent potential cross-site scripting (XSS) attacks, it's recommended to use htmlspecialchars() to HTML-encode any data before outputting it to the browser.

The above is the detailed content of Do Prepared Statements Need `mysql_real_escape_string()` for Security?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn