What steps should be taken to ensure proper database connection and query execution in PHP scripts?
To ensure proper database connection and query execution in PHP scripts, it is important to establish a secure and reliable connection to the database using appropriate credentials, handle errors effectively, and sanitize input to prevent SQL injection attacks.
<?php
// Establishing a database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Executing a query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- What are the advantages and disadvantages of using meta-refresh tags versus PHP scripts for updating image files with new date and time information on a webpage?
- How can one handle or avoid the issue of receiving unexpected characters at the beginning of an XML file when using file_get_contents in PHP?
- What are some best practices for updating content in a specific <div> element without reloading the entire page in PHP?