Happy Coding
Home
Previous
In this post, we will learn about how to use query SELECT in PHP for retrieve data from database MySQL, with 3 ways:
For known, how to connect to database, can be learned in here
Insert query is used for insert data or record into database
Syntax:
SELECT column1, column2, column3
FROM table_name;
using wilcard (*) for select all column
SELECT *
FROM table_name;
Example:
$sql = "SELECT id, firstname, lastname ";
$sql .= "FROM users " ;
$sql = "SELECT * ";
$sql .= "FROM users " ;
And, for execute the query, we will use 3 ways:
1. MySQLi1 procedural
Execute query using mysqli::query2 and get a $result
:
$result = mysqli_query( $connection, $sql );
Display data using mysqli_result::fetch_assoc3, alternative using mysqli_result::fetch_object4:
echo "<pre>";
echo "No \t";
echo "ID \t";
echo "Firstname \t\t";
echo "Lastname \n";
$no = 1; /* variabel $no */
/* loop while */
while ( $row = mysqli_fetch_assoc($result) )
{
echo $no . "\t";
echo $row['id'] . "\t";
echo $row['firstname'] . "\t\t";
echo $row['lastname'] . "\n";
$no++; /* increment */
}
echo "</pre>";
Close connection using mysqli::close5:
mysqli_close($connection);
Source Code:
2. MySQLi1 object-oriented
Execute query using mysqli::query2 and get a $result
:
$result = $connection->query($sql);
Display data using mysqli_result::fetch_object4:
echo "<pre>";
echo "No \t";
echo "ID \t";
echo "Firstname \t";
echo "Lastname \n";
$no = 1; /* variabel $no */
/* loop while */
while ( $row = $result->fetch_object() )
{
echo $no . "\t";
echo $row->id . "\t";
echo $row->firstname . "\t\t";
echo $row->lastname . "\n";
$no++; /* increment */
}
echo "</pre>";
Close connection using mysqli::close5:
$connection->close();
Source Code:
3. PDO6
Execute query and get a $result
:
$result = $connection->query($sql);
Display Data:
echo "<pre>";
echo "No \t";
echo "ID \t";
echo "Firstname \t";
echo "Lastname \n";
$no = 1; /* variabel $no */
/* loop foreach */
foreach ( $result as $row )
{
echo $no . "\t";
echo $row->id . "\t";
echo $row->firstname . "\t\t";
echo $row->lastname . "\n";
$no++; /* increment */
}
echo "</pre>";
Close connection:
$connection = null;
Source Code:
Back to Home
| Next#
-
php.net, "MySQL Improved Extension", accessed on date 21 december 2019 and from https://www.php.net/manual/en/book.mysqli.php ↩
-
php.net, "mysqli::query", accessed on date 22 december 2019 and from https://www.php.net/manual/en/mysqli.query.php ↩
-
php.net, "mysqli_result::fetch_assoc", accessed on date 23 december 2019 and from https://www.php.net/manual/en/mysqli-result.fetch-assoc.php ↩
-
php.net, "mysqli_result::fetch_object", accessed on date 23 december 2019 and from https://www.php.net/manual/en/mysqli-result.fetch-object.php ↩
-
php.net, "mysqli::close", accessed on date 21 december 2019 and from https://www.php.net/manual/en/mysqli.close.php ↩
-
php.net, "PDO::__construct", accessed on date 21 december 2019 and from https://www.php.net/manual/en/pdo.construct.php ↩
Top comments (0)