Select Data From a MySQL Database using PHP
ID | Name | Class | Subject |
1 | Anuj Sharma | 2nd | Math |
2 | Rahul | 3rd | Scince |
3 | Pooja | 2nd | English |
4 | Rohan | 2nd | Art |
Object-oriented
<?php
$servername = "localhost";
$username = "username"; // when you work in your computer then use username name "root"
$password = "password"; // when you work in your computer then use password Empty
$dbname = "yourdatabase";//Type Your Database Name Here
// In this line Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// In this line Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// In this line fet data from table
//(*) use when we want all field data
// when we want particular field then use like this type query
// exmple $sql = "SELECT name,class FROM tbl_student_record";
$sql = "SELECT * FROM tbl_student_record";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. "<br>";
echo "Name: " . $row["Name"]. "<br>";
echo "Class: " . $row["Class"]. "<br>";
echo "Subject: " . $row["Subject"]. "<br>";
echo "<hr>";
}
} else {
echo "record is empty";
}
$conn->close();
?>
Procedural
<?php
$servername = "localhost";
$username = "username"; // when you work in your computer then use username name "root"
$password = "password"; // when you work in your computer then use password Empty
$dbname = "yourdatabase";//Type Your Database Name Here
// In this line Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// In this line Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// In this line fet data from table
//(*) use when we want all field data
// when we want particular field then use like this type query
// exmple $sql = "SELECT name,class FROM tbl_student_record";
$sql = mysqli_query($conn,"SELECT * FROM tbl_student_record")or die(mysqli_error();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. "<br>";
echo "Name: " . $row["Name"]. "<br>";
echo "Class: " . $row["Class"]. "<br>";
echo "Subject: " . $row["Subject"]. "<br>";
echo "<hr>";
}
} else {
echo "record is empty";
}
mysqli_close($conn);
?>
Output
output
ID: 1 Name: Anuj Sharma Class: 2nd Subject: Math
ID: 2 Name: Rahul Class: 3nd Subject: Scince
ID: 3 Name: Pooja Class: 2nd Subject: English
ID: 4 Name: Rohan Class: 2nd Subject: Art
Quick ask your Question
- Connect mysql database using php Language
- Insert record into MySQL Database Using PHP Language
- Get Record from MySQL Database in PHP
- Update Record from MySQL Database in PHP
- Delete Record From a MySQL Database using PHP
- Insert Multiple Records into MySQL with a Single Query
- Create MySQL Database Using PHP
- Create Table in MySQL Database Using PHP