This tutorial will demonstrate how to retrieve data from tables. LEVEL : BEGINNER I assume that you have read tutorial of adding data into tables. Read here. I will ty my best to keep it as easy as I can. Functions we will use : mysql_fetch_assoc(); mysql_num_rows();Ok - now I assume that you have read the above tutorial I mentioned in which we inserted data into table name as members. Now suppose we have a table named as "members" and it has the following fields. id, name and email.and we have 3 members registered (means we have 3 rows) here they are (the data in members table) 1 Roman abc@swish-db.com 2 Imran xyz@swish-db.com 3 Kamran asd@swish-db.com so these are the total values inserted in table "members". Now I will make a PHP file fetch.php which will retrieve data from members table.
$res=mysql_query("SELECT * FROM members"); if(mysql_num_rows($res)==0) echo "There is no data in the table"; else
for($i=0;$i$row=mysql_fetch_assoc($res); echo "ID : $row[id] Name : $row[name] Email : $row[email]"; } ?>What is mysql_num_rows ?
This function returns the number of rows effected by SELECT statement. You can use different clauses in SELECT statement, for exmaple you retriev the name of member whose ID is 2. which is IMRAN, so you will use query like this. If there is not data in table it will diplay the error "There is no data in the table"..
$res=mysql_query("SELECT name FROM members WHERE id=2");
now we have used WHERE clause in the above statement.
What is mysql_fetch_assoc() ?
This function fetches a a result row as associatve array, and returns an associatve array. In other meaning it fetches the result from the row.
In the for() loop I have displayed the fetched result. So the output of this file will be
1 Roman abc@swish-db.com 2 Imran xyz@swish-db.com 3 Kamran asd@swish-db.com
NOTE : Dont forget to include config.php at the top, or in simple words, dont forget to connect to mysql before you check the fetch.php
I hope it was very easy to understand, however if you have ny questions please feel free to ask. regards - Ali..
|