Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP MySQL reads the data


May 11, 2021 PHP


Table of contents


PHP MySQL reads the data

When PHP is connected to the MySQL database, do you need to read data to the database? S o how do you read it? Let's see.

Read data from the MySQL database

Select statements are used to read data from a data table:

SELECT column_name(s) FROM table_name

We can read the fields in all data tables using the number:

SELECT * FROM table_name

To learn more about SQL, visit our SQL tutorial.

In the following example we read the data for the id, firstname, and lastname columns from the table MyGuests and display it on the page:

Instances (MySQLi - Object Oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
Detect the 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 each row of data
while($row = $result->fetch_assoc()) {
echo "id: ". $ row["id"]. " - Name: ". $ row["firstname"]. " " . $ row["lastname"]. "<br>";
}
} else {
echo "0 results";
}


mysqli_close($conn);
?>


The following instance reads all the records of the MyGuests table and displays them in the HTML table:

Example (PDO)

<?php
echo "<table style='border: solid 1px black;' >";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th><th>Email</th><th>Reg date</th></tr>";

class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width: 150px; b order: 1px solid black; ' >" . p arent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM MyGuests");
$stmt->execute();

Set the result set to an associated array
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
$dsn = null;
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>