What are the best practices for handling database connections and queries in PHP scripts to ensure data is displayed correctly on a website?
When handling database connections and queries in PHP scripts, it is important to properly establish a connection to the database, sanitize input data to prevent SQL injection attacks, and handle errors gracefully to ensure data is displayed correctly on a website.
// Establish a connection 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);
}
// Sanitize input data
$id = mysqli_real_escape_string($conn, $_GET['id']);
// Perform a query
$sql = "SELECT * FROM table WHERE id = $id";
$result = $conn->query($sql);
// Handle errors
if (!$result) {
die("Error: " . $conn->error);
}
// Display data on the website
while ($row = $result->fetch_assoc()) {
echo $row['column'];
}
// Close the connection
$conn->close();
Related Questions
- What are the potential pitfalls of direct variable assignments in PHP classes and how can they impact memory usage?
- How can PHP developers ensure the security of file downloads initiated by their code?
- Are there any best practices for setting up PHP scripts and ensuring they run correctly on a local server environment?