Home >Backend Development >PHP Tutorial >Why Does `mysqli_real_escape_string()` Throw 'expects exactly 2 parameters, 1 given'?

Why Does `mysqli_real_escape_string()` Throw 'expects exactly 2 parameters, 1 given'?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 14:50:10378browse

Why Does `mysqli_real_escape_string()` Throw

Resolving "mysqli_real_escape_string() expects exactly 2 parameters, 1 given" Error

The "mysqli_real_escape_string()" function is designed to escape special characters in a string to prevent SQL injection attacks. However, it has a specific parameter requirement that may cause the error "mysqli_real_escape_string() expects exactly 2 parameters, 1 given."

Problem Analysis:

The provided code checks the PHP version and attempts to use "mysqli_real_escape_string()" accordingly. However, the function call only includes the string to be escaped, missing the first required parameter: the mysqli link.

Documentation Explanation:

According to the official documentation, "mysqli_real_escape_string()" requires two parameters:

  1. mysqli $link: A reference to an established MySQLi connection.
  2. string $escapestr: The string to be escaped.

Solution:

To resolve the error, the code should include both parameters when calling the "mysqli_real_escape_string()" function. Here's an updated version:

if (phpversion() >= '4.3.0') {
    $string = mysqli_real_escape_string($link, $string);
} else {
    $string = mysqli_escape_string($link, $string);
}

By ensuring that the mysqli link is provided as the first parameter, the "mysqli_real_escape_string()" function will properly escape the input string and prevent SQL injection vulnerabilities.

The above is the detailed content of Why Does `mysqli_real_escape_string()` Throw 'expects exactly 2 parameters, 1 given'?. 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