What are common pitfalls when using PHP to interact with a database, as seen in the provided script?
One common pitfall when using PHP to interact with a database is not properly sanitizing user input, which can lead to SQL injection attacks. To solve this issue, always use prepared statements or parameterized queries to securely pass user input to the database.
// Original script with SQL injection vulnerability
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Fixed script using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
Related Questions
- How can PHP be used to send emails with attachments stored on the server?
- What are the potential pitfalls of continuously appending text to a file using PHP?
- In what ways can the use of absolute paths versus relative paths impact the loading of resources like CSS files in PHP projects, and how can this be effectively managed?