How to SELECT from a table, part I.
TAGS: SQL, SELECT, PHP, MySQL


Welcome back.

In the last posting I tried to explain how to write some values taken from a HTML form, into a database that we created in an earlier post.

So, I expect that you have created the Database and the Table, and that you have populated the database with some contacts. Because now we will be reading those contacts.
Below here is the simple PHP code that does one simple thing – it reads the First and Last names of alle the contacts, and make their name a link, linking to their emailaddress, as found in the database.

Copy the below code into a file, name it 'read.php', then call it in your browser;
http://127.0.0.1/read.php


<?php 

$con = mysqli_connect('127.0.0.1', 'root', 'Your_Password', 'dbname'); 

if (mysqli_connect_errno()) { 
  echo 'Error connecting to DB'; 
} 

$SQL_String = mysqli_query($con, 'SELECT * FROM 
contacts ORDER BY AutoID ASC'); 

while($row = mysqli_fetch_array($SQL_String))  { 
  echo "<A HREF='mailto:" . $row['EmailAddr'] . "'>" .  
  $row['Firstname'] . " " . $row['Lastname'] . "</A>
"; } ?>
So, now you can list all the entries in the database, and in the example given here, you can see how you can build a link using some of the values.
Because there are several entries in the database we make use of WHILE. So we can loop through all rows, and display them on a webpage. In the next example we will look at selecting only one entry from the database. Hang on for the next blog. We continue learning about reading from a SQL database using PHP. SELECT.