How can the mysql_query() function be effectively used to fetch and display results in PHP?
To effectively use the mysql_query() function to fetch and display results in PHP, you need to establish a database connection, execute the query, fetch the results, and then display them in a desired format. It is important to handle any potential errors that may occur during the process.
// Establish database connection
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Fetch and display results
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
mysqli_close($connection);
Related Questions
- How can you use switch statements in PHP to display different values based on database results?
- What are the potential security risks of storing all relevant CMS files in a password-protected backend folder?
- Are there any specific PHP functions or methods that assist with center-aligning text in HTML?