PHP Select Data From MySQL


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




The following example selects the id, firstname and lastname columns from the MyGuests table and displays it in Table formate

Example (MySQL)

<?php
include("mysql_connection.php");
$sql="select id, firstname, lastname from fa_MyGuests";
$query=mysql_query($sql);
if($query)
{
?>
<?php include('header1.php'); ?>
<?php include("mysql_sidemenu.php"); ?>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="table-responsive">

<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while($row=mysql_fetch_array($query))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
<?php
}
}?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php include('footer.php');?>


mysql_connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysql_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysql_error());
}
$db=mysql_select_db("lipsphpstudent");
?>
mysql_select_live_example.php
<?php
include("mysql_connection.php");
$sql="select id, firstname, lastname from fa_MyGuests";
$query=mysql_query($sql);
if($query)
{
?>
<?php include('header1.php'); ?>
<?php include("mysql_sidemenu.php"); ?>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="table-responsive">

<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while($row=mysql_fetch_array($query))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
</tr>
<?php
}
}?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php include('footer.php');?>