What are some common pitfalls to avoid when using PHP MySQLi for database operations?
One common pitfall to avoid when using PHP MySQLi for database operations is not properly sanitizing user input, which can leave your application vulnerable to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.
// Example of using prepared statements with parameterized queries to avoid SQL injection
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param("s", $username);
// Execute the statement
$stmt->execute();
// Bind the result
$stmt->bind_result($result);
// Fetch the result
$stmt->fetch();
// Close the statement and connection
$stmt->close();
$mysqli->close();