What are some common pitfalls when trying to access and display data from a MySQL database using PHP?
One common pitfall when accessing and displaying data from a MySQL database using PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries. Another pitfall is not handling errors properly, which can lead to security vulnerabilities or unexpected behavior. Always check for errors and handle them appropriately in your code.
// Connect to MySQL 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 table WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
// Display data
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
echo "Email: " . $row["email"] . "<br>";
}
// Close connection
$stmt->close();
$conn->close();
Keywords
Related Questions
- What is the best practice for handling user input in PHP to prevent SQL injection when sorting a table?
- In the context of PHP programming, what are the advantages and disadvantages of using pass by value or pass by reference for passing configuration values to functions?
- Can you suggest any resources or tutorials for beginners to learn how to effectively use xPATH with PHP to work with XML files?