In the provided PHP script, what are the implications of not escaping variables in SQL queries and how can this be improved?
Not escaping variables in SQL queries can lead to SQL injection attacks, where malicious code can be injected into the query and potentially compromise the database. To improve this, you can use prepared statements with parameterized queries, which automatically escape and sanitize input data.
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Improved code using prepared statements
$stmt = $connection->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();