How to fetch data from database using php and mysql (OPP)
To fetch data from a MySQL database using PHP and the mysqli extension, you can follow these steps:
- Connect to the database: Create a database connection using the mysqli_connect function. This will create a connection to the MySQL server with the specified hostname, username, and password.
$conn = mysqli_connect("hostname", "username", "password", "database");
- Write a SQL query to fetch data: Write a SQL query to fetch the data you want from the database. For example, to fetch all data from a table named "users":
$sql = "SELECT * FROM users";
- Execute the query: Use the mysqli_query function to execute the SQL query and return a result set.
$result = mysqli_query($conn, $sql);
- Loop through the result set and fetch data: Use the mysqli_fetch_assoc function to fetch one row of data from the result set at a time. This function returns an associative array with the column names as keys and the row data as values. You can then use this data to display it on your webpage or use it in other ways.
while ($row = mysqli_fetch_assoc($result)) {
// Do something with the row data, such as display it on a webpage
echo $row["username"] . "<br>";
}
- Free the result set: When you're finished fetching data, be sure to free the result set using the mysqli_free_result function.
mysqli_free_result($result);
- Close the database connection: When you're finished working with the database, be sure to close the connection using the mysqli_close function.
mysqli_close($conn);
Putting it all together, the PHP code to fetch data from a MySQL database might look something like this:
<?php
// Step 1: Connect to the database
$conn = mysqli_connect("hostname", "username", "password", "database");
// Step 2: Write a SQL query to fetch data
$sql = "SELECT * FROM users";
// Step 3: Execute the query
$result = mysqli_query($conn, $sql);
// Step 4: Loop through the result set and fetch data
while ($row = mysqli_fetch_assoc($result)) {
// Do something with the row data, such as display it on a webpage
echo $row["username"] . "<br>";
}
// Step 5: Free the result set
mysqli_free_result($result);
// Step 6: Close the database connection
mysqli_close($conn);
?>
This is just a basic example, and there are many ways to customize and refine your database queries and data fetching methods.