Select Data from Database

PHP MySQL Select Data
  • To retrieve the data from data table used select query used.
MySQLi Object-Oriented

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, first_name, second_name, email FROM student_data";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - first name: " . $row["first_name"]. " - second name" . $row["second_name"]. " - email: " . $row["email"]. "
";
}
} else {
echo "0 results";
}
$conn->close();
?>

MySQLi Procedural

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

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, first_name, second_name, email FROM student_data";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["second_name"]. "- email: " . $row["email"]. "
";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

PDO

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th><th>email</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 = "student";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, first_name, second_name, email FROM student_data");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

$conn = null;
echo "</table>";
?>

PHP MySQL Limit Data Selections

  • To show a limited data to used LIMIT Clause. this Clause used to to show multi page result of pagination.

Syntax

$sql = "SELECT * FROM Orders LIMIT 30";

$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";

$sql = "SELECT * FROM Orders LIMIT 15, 10";