Home > Database > Mysql Tutorial > body text

How do Parameterized Queries in PHP Protect Against SQL Injection?

Mary-Kate Olsen
Release: 2024-10-28 06:00:03
Original
872 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!