What is the difference between using mysqli_connect() and mysqli_query() in PHP when fetching data from a database?
When fetching data from a database in PHP, it's important to understand the difference between mysqli_connect() and mysqli_query(). mysqli_connect() is used to establish a connection to the database, while mysqli_query() is used to execute a query on the database. To fetch data, you need to first establish a connection using mysqli_connect() and then execute a query using mysqli_query() to retrieve the data.
// Establish a connection to the database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a query to fetch data
$query = "SELECT * FROM table_name";
$result = mysqli_query($conn, $query);
// Fetch and display the data
while ($row = mysqli_fetch_assoc($result)) {
echo "Column 1: " . $row["column1"] . " - Column 2: " . $row["column2"] . "<br>";
}
// Close the connection
mysqli_close($conn);