How to Select Data in Database Using PHP MySQL?
Hi Dev,
This tutorial will provide example of how to select data in database using php mysql. This tutorial will give you simple example of how to fetch data from the database in php. this example will help you php mysql select data. we will help you to give example of how can i get specific data from mysql in php. Alright, let’s dive into the steps.
In php web application we wish to select data from mysql database then first establish connection between php web application and mysql database. and the following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:
Example 1:
index.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$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["firstname"]. " " . $row["lastname"].;
}
}else{
echo "0 results";
}
$conn->close();
?>
Output:
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
I hope it could help you...
- How to Increase max_connections in MySQL?
- How to Install the PHP PDO MySQL Extension on Ubuntu 22.04?
- How to Install PHP MySQL on Linux Ubuntu?
- How to Install LEMP Stack Nginx, MySQL, PHP on Ubuntu?
- How to Change MySQL Root User Password Ubuntu?
- PHP 8 MySQL Form Validation Example
- How to Select First Row Only in PHP MySQL?
- How To Backup MySQL Database Using PHP Example