Home >Database >Mysql Tutorial >Why Are Prepared Statements in MySQLi Essential for Secure Database Interactions?
In your code snippet, you're encountering an error while executing prepared statements due to the absence of parameter binding. According to the MySQLi documentation, parameter markers in prepared statements must be bound to application variables using mysqli_stmt_bind_param before execution.
To rectify the error, modify your code as follows:
$name = 'one'; $age = 1; $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?,?)"); // Bind parameters to application variables (string & integer in this case) $stmt->bind_param('si', $name, $age); // Execute the prepared statement after binding $stmt->execute();
Using MySQLi for prepared statements is recommended due to its enhanced security features. Prepared statements prevent SQL injection vulnerabilities by separating the query from the values, reducing the risk of malicious code being injected into your database.
Here's a complete example of prepared statements, covering connection, insertion, and selection with error handling:
<?php // Database connection $mysqli = new mysqli("localhost", "root", "root", "test"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; exit; } // Prepare statement for insertion $stmt = $mysqli->prepare("INSERT INTO users (name, age) VALUES (?, ?)"); if (!$stmt) { echo "Error preparing statement: " . $mysqli->error; exit; } // Bind parameters and execute insertion $name = 'one'; $age = 1; $stmt->bind_param('si', $name, $age); if (!$stmt->execute()) { echo "Error executing statement: " . $stmt->error; exit; } // Prepare statement for selection $stmt = $mysqli->prepare("SELECT name, age FROM users WHERE id = ?"); if (!$stmt) { echo "Error preparing statement: " . $mysqli->error; exit; } // Bind parameter and execute selection $id = 1; $stmt->bind_param('i', $id); if (!$stmt->execute()) { echo "Error executing statement: " . $stmt->error; exit; } // Retrieve and display results $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { echo "Name: " . $row['name'] . ", Age: " . $row['age'] . "<br>"; } // Close statement and connection $stmt->close(); $mysqli->close(); ?>
This example includes error handling at each step, ensuring the proper execution of queries and providing informative error messages in case of any issues.
The above is the detailed content of Why Are Prepared Statements in MySQLi Essential for Secure Database Interactions?. For more information, please follow other related articles on the PHP Chinese website!