PHP/MySQL - Get Table Data


/ Published in: PHP
Save to your folder(s)

Use this function to print out all the rows in a table. Specify columns to show using the columnstring parameter:
tablulardata(tablename, columnstring);
ie:
tabluardata("users","username=Username|fname=First Name|lname=Last Name");


Copy this code and paste it in your HTML
  1. function tabulardata($tablename,$columnstring){
  2. $columns = explode("|",$columnstring);
  3. $field_query = mysql_query("SELECT * FROM ".$tablename."");
  4. if(mysql_num_rows($field_query) > 0){
  5. //Get field data
  6. echo("<table>\n");
  7. echo("<tr>\n");
  8. $columnnames = array();
  9. foreach($columns as $column){
  10. if(strstr($column,"=")){
  11. $columninfo = explode("=",$column);
  12. $columntitle = $columninfo[1];
  13. $columnnames[] = $columninfo[0];
  14. }else{
  15. $columntitle = $column;
  16. $columnnames[] = $column;
  17. }
  18. echo("<td>".$columntitle."</td>\n");
  19. }
  20. echo("</tr>\n");
  21. while($field_array = mysql_fetch_array($field_query)){
  22. echo("<tr>\n");
  23. foreach($field_array as $field_key=>$field_value){
  24. if(in_array($field_key,$columnnames) && $field_key != ""){
  25. echo("<td>".$field_value."</td>\n");
  26. }
  27. }
  28. echo("</tr>\n");
  29. }
  30. echo("</table>");
  31.  
  32. }
  33. }

URL: http://www.jeffkilroy.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.