What are some common mistakes to avoid when coding in PHP, based on the provided code snippet?
One common mistake to avoid when coding in PHP is not properly escaping user input before using it in SQL queries, which can lead to SQL injection attacks. To solve this issue, it is recommended to use prepared statements with parameterized queries to prevent SQL injection vulnerabilities.
// Incorrect way to query database with user input (vulnerable to SQL injection)
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysqli_query($connection, $query);
// Correct way to query database with user input (using prepared statements)
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "s", $user_input);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);