PHP MySQL Select Data Using In PageĀ  ā€“ The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:

Select Data From a MySQL Database

The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

Example (MySQLi Object-oriented)

<?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();
?>

Code lines to explain from the example above:

First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result.

The post PHP MySQL Select Data Using In Page appeared first on PHPFOREVER.

By

Leave a Reply

X