Fetch Data from MySQL (PHPMyAdmin).
First, this is an example code for fetching or retrieving data from the database, so take it as an inspiration and set the structure of the table and variable names according to your needs.
Follow the given steps.
- This is the database and table structure from where we are fetching the data.
-- Creating DATABASE
CREATE DATABASE fetchfromdb
-- Creating Table
CREATE TABLE `fetchfromdb`.`formfields` (
`id` INT NOT NULL auto_increment,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(50) NOT NULL,
`submit date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) engine = innodb;
- This is the connection we are making in PHP for fetching the data.
// Creating Variables
$server_name = "localhost";
$user_name = "root";
$password = "";
$db_name = "fetchfromdb";
// Creating Connection
$conn = new mysqli($server_name, $user_name, $password, $db_name);
// Checking Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
- Now, this is the particular PHP script to fetch and print the data.
// Selecting all data
$sql = "SELECT * FROM `formfields`;";
$result = $conn->query($sql);
// Checking if empty
if ($result->num_rows > 0) {
// Separating in rows
while ($row = $result->fetch_assoc()) {
echo $row['ID'] . " - ID" . "<br>";
echo $row['Name'] . " - Name" . "<br>";
echo $row['Email'] . " - Email" . "<br>";
echo $row['Submit Date'] . " - Submit Date" . "<br>";
}
} else {
echo "0 results";
}
- All set:)
In Addition
- The entire code at once
<?php
// Creating Variables
$server_name = "localhost";
$user_name = "root";
$password = "";
$db_name = "fetchfromdb";
// Creating Connection
$conn = new mysqli($server_name, $user_name, $password, $db_name);
// Checking Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Selecting all data
$sql = "SELECT * FROM `formfields`;";
$result = $conn->query($sql);
// Checking if empty
if ($result->num_rows > 0) {
// Separating in rows
while ($row = $result->fetch_assoc()) {
echo $row['ID'] . " - ID" . "<br>";
echo $row['Name'] . " - Name" . "<br>";
echo $row['Email'] . " - Email" . "<br>";
echo $row['Submit Date'] . " - Submit Date" . "<br>";
}
} else {
echo "0 results";
}
// Closing Connection
$conn->close();
?>
0 Comments