What are common pitfalls when trying to read data from a MySQL database using PHP?
One common pitfall when trying to read data from a MySQL database using PHP 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 interact with the database.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = $_POST['username']; // Assuming user input is coming from a form
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the connection
$stmt->close();
$conn->close();