What are some best practices for accessing and manipulating data from MySQL databases in PHP?
When accessing and manipulating data from MySQL databases in PHP, it is important to use prepared statements to prevent SQL injection attacks. This involves using placeholders in SQL queries and binding parameters to those placeholders. Additionally, it is recommended to properly handle errors and exceptions that may occur during database operations.
// 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 SELECT statement using prepared statements
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
// Fetch and display results
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
}
// Close statement and connection
$stmt->close();
$conn->close();
Related Questions
- How can PHP developers address the issue of \n characters being converted to new lines when outputting data from a database in a <textarea>?
- How does PHP handle comparisons between boolean values and integers in conditional statements?
- What is responsive design and how can it help address issues with website display on different devices?