What best practices should be followed when using mysqli_query for SQL queries in PHP?
When using mysqli_query for SQL queries in PHP, it is important to follow best practices to prevent SQL injection attacks. One way to do this is by using prepared statements with placeholders for user input data, rather than directly inserting user input into the query. This helps to sanitize the input and protect against malicious SQL injections.
// Example of using prepared statements with mysqli_query
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare the SQL query with a placeholder for user input
$query = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind the user input to the placeholder
$query->bind_param("s", $username);
// Set the user input data
$username = $_POST['username'];
// Execute the query
$query->execute();
// Get the result set
$result = $query->get_result();
// Fetch the data
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the query and database connection
$query->close();
$mysqli->close();