What are some common pitfalls to avoid when using mysql_query in PHP for database operations?
One common pitfall to avoid when using mysql_query in PHP is the vulnerability to SQL injection attacks. To prevent this, it is recommended to use prepared statements with parameterized queries instead. This helps sanitize user input and prevent malicious queries from being executed.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a 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();
// Fetch the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();