What are the potential pitfalls of using PHP to interact with a MySQL database?
One potential pitfall of using PHP to interact with a MySQL database is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements or parameterized queries to securely pass user input to the database.
// Example of using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();
// Process results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process each row
}
// Close statement and connection
$stmt->close();
$mysqli->close();