|
[back] Outputting Data Let's see what is in our table! <?php mysql_connect(localhost,$username,$password); $query="SELECT * FROM students"; $num=mysql_numrows($result); echo "<b><center>Database Output</center></b><br><br>"; $i=0; echo "first: $first<br> last: $last<br>graduation
year: $grad_year<br>student number: $student_no<p>";
<?php mysql_connect(localhost,$username,$password); Log in in the usual way. $query="SELECT * FROM contacts"; Again, we will just change the $query variable with "SELECT * FROM students" to select the desired information. In this case the whole contents of the database is now contained in a special array with the name $result. Before you can output this data you must change each piece into a separate variable. There are three stages to this. First: Counting Rows The first thing that we need to know is how many database rows there are. You could, of course, just type this in but it is not a very good solution as the whole script would need to be changed every time a new row was added. $num=mysql_numrows($result); The above line will set the value of $num to be the number of rows stored in $result. This can then be used in a loop to get all the data and output it on the screen. Second: Setting Up A Loop You must now set up a loop to take each row of the result and print out the data held there. By using $num, which you created above, you can loop through all the rows quite easily. In the code below, $i is the number of times the loop has run and is used to make sure the loop stops at the end of the results so there are no errors. $i=0; This is the same thing that we did with our basic PHP loops. - ($i < 10) This PHP loop will execute the code the correct number of times. Each time $i will be one greater than the time before. Remember from our PHP exercise that the computer counts the first row of an array as 0 (zero). This is why we set $i=0; to zero. Third: Assigning The Data To Variables The final part of this output script is to assign each piece of data to its own variable. The following code is used to do this: $variable=mysql_result($result,$i,"fieldname"); So to take each individual piece of data in our database we would use the following: $first=mysql_result($result,$i,"first"); Note: Although we could get the ID field in the same way, there really is no need to have it at this point. We will use it on later scripts. Now we can display each variable: echo "first: $first<br> last: $last<br>graduation year: $grad_year<br>student number: $student_no<p>"; Create a new PHP page and save it as display1.php |