Home  >  Article  >  Database  >  How do Parameterized Queries in PHP Protect Against SQL Injection?

How do Parameterized Queries in PHP Protect Against SQL Injection?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 06:00:03873browse

How do Parameterized Queries in PHP Protect Against SQL Injection?

Parameterized Queries in PHP with MySQL Connection

In the realm of web development, SQL injection poses a significant security threat. By concocting malicious queries, attackers can bypass authentication mechanisms and access sensitive data. Parameterized queries offer a foolproof solution to this vulnerability.

Let's consider a snippet of code from a PHP login page that falls short of safeguarding against SQL injection:

<code class="php">$userName = $_POST["username"];
$userPass = $_POST["password"];

$query = "SELECT * FROM users WHERE username = '$userName' AND password = '$userPass'";

$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);

if (!$row) {
    echo "No existing user or wrong password.";
}</code>

To employ parameterized queries, we need to establish a connection to the database and prepare a parameterized statement. The following code provides a modified example:

<code class="php">$stmt = mysqli_prepare($dbc, "SELECT * FROM users WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($stmt, "s", $userName);
mysqli_stmt_bind_param($stmt, "s", $userPass);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);</code>

Here's a breakdown of the code:

  • mysqli_prepare() prepares a parameterized statement with placeholders (?) representing the parameters.
  • mysqli_stmt_bind_param() binds the values to the placeholder parameters.
  • mysqli_stmt_execute() executes the parameterized statement.
  • mysqli_stmt_fetch() retrieves the result rows.

In this parameterized query, the placeholders prevent the injection of malicious input as they are replaced by bound values. Moreover, it's essential to encrypt or hash passwords for enhanced security, avoiding the storage of plaintext passwords. By adopting parameterized queries, PHP developers can effectively safeguard their web applications from SQL injection attacks.

The above is the detailed content of How do Parameterized Queries in PHP Protect Against SQL Injection?. 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