|
This tutorial goes along with several others that use the same news database such as Add a Row to mySQL, Deleting a Row, and Edit a Row In mySQL. We have a database called spoono_news, with a table called news. In the mySQL news table, we have 6 fields: id, title, message, who, date, and time. Here is a simple tutorial on displaying information from a mySQL database: <? //connect to mysql //change user and password to your mySQL name and password mysql_connect("localhost","user","password"); //select which database you want to edit mysql_select_db("spoono_news");
//select the table $result = mysql_query("select * from news");
//grab all the content while($r=mysql_fetch_array($result)) { //the format is $variable = $r["nameofmysqlcolumn"]; //modify these to match your mysql table columns $title=$r["title"]; $message=$r["message"]; $who=$r["who"]; $date=$r["date"]; $time=$r["time"]; $id=$r["id"]; //display the row echo "$title <br> $message <br> $who <br> $date | $time <br>"; } ?> The first two lines connect to the mySQL and lets you select the database you want to display. The $result variable runs a query to get all the rows from the table. The while loop on the next line lets you display each result row my row. Inside the while loop are declarations for each column in the database. The last line of the loop echos out each of the sections.
Now say you want to order the results and display them alphabetically by the "who" field. Well, all you have to do is edit the $result tag from above to: $result = mysql_query("select * from news order by who"); Not too tough was it? Well, the last thing we want to cover is how to set limits by only showing the first 30 results. Well simply change the $result code again: $result = mysql_query("select * from table limit 30"); Credit: www.spoono.com
|