What are the potential risks of using mysqli_query without prepared statements in PHP?
Using mysqli_query without prepared statements in PHP can expose your application to SQL injection attacks. Prepared statements help prevent this by separating SQL logic from user input, making it impossible for malicious input to alter the structure of the SQL query. To mitigate this risk, always use prepared statements when executing SQL queries in PHP.
// Example of using prepared statements with mysqli in PHP
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL query using a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind user input to the placeholder
$stmt->bind_param("s", $username);
// Set the user input and execute the query
$username = "john_doe";
$stmt->execute();
// Get the results
$result = $stmt->get_result();
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();