PhpMySQL Read Data Reading data from MySQL database
The SELECT statement is used to read data from the data table:
SELECT column_name (s) from table_name
To learn more about SQL, please visit our SQL Tutorial.
In the following example we read the IDs, FirstName and LastName columns of data from table myguests and display them on the page:
Instance (mysqli-object-oriented) <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "MyDB";
Create a connection
$conn = new Mysqli ($servername, $username, $password, $dbname);
detecting connections
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 per row of data
while ($row = $result->fetch_assoc ()) {
echo "<br> ID:". $row ["id"]. "-Name:". $row ["FirstName"]. " " . $row ["LastName"];
}
} else {
echo "0 results";
}
$conn->close ();
?>
The following instance reads all the records from the Myguests table and displays them in the HTML table:
Instance (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; border:1px solid black; ' > ". Parent::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;d bname= $dbname", $username, $password);
$conn->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
$stmt = $conn->prepare ("SELECT * from myguests");
$stmt->execute ();
Set result set to associative array
$result = $stmt->setfetchmode (PDO::FETCH_ASSOC);
foreach (New TableRows recursivearrayiterator ($stmt->fetchall ())) as $k = = $v) {
Echo $v;
}
$DSN = null;
}
catch (Pdoexception $e)
{
echo "Error:". $e->getmessage ();
}
$conn = null;
echo "</table>";
?>
PHP MySQL Read Data