PHP Select Data From MySQL

You can use the php statement to get the data from MySQL database. Check the example below.

Example Code:

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check 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 data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " – Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>[/php]

Code Explanation:

First, we will connect to our database by using connect database php query.

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

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

Then we will run the $sql query.
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

In the SQL query, we are asking php script to select the id, firstname, lastname from the database MyGuests.

On the next line we created another variable called $resut which is equal to $conn and query($sql)

Then we are running if statement.

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
";
}
} else {
echo "0 results";
}

In the if statement we have created the array with the key $result and value num_row which is bigger than 0.

Then we have run the statement with the while function and assigned the variable $row to $result to fetch_assoc() row.

To get the data we have created the echo statement with each individual field id, firstname and lastname.

Related Posts

Leave a Reply