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:
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!