What are the potential pitfalls of using the mysql_query() function in PHP for database operations?
Using the mysql_query() function in PHP for database operations can lead to SQL injection vulnerabilities as it does not provide proper escaping of user input. To prevent this, you should use parameterized queries with prepared statements or use mysqli or PDO extensions for database operations.
// Using mysqli 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 = "john_doe";
$stmt->execute();
// Fetch result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close statement and connection
$stmt->close();
$mysqli->close();