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
- What are some alternative methods or functions in PHP that could be used to read a CSV file more efficiently into a database table?
- How can PHP developers ensure that the output of their scripts accurately reflects the data stored in multiple tables, as shown in the forum discussion?
- How can PHP libraries like PHPExcel be utilized to enhance data export functionality in PHP applications?