Skip to main content

[Template] PHP显示MySQL数据



只需要修改数据库的信息。
  1. <html>
  2. <head>
  3. <title>View Database</title>
  4. <body>

  5. <?php
  6. //connect database
  7. $db_host = 'localhost';
  8. $db_user = 'username';
  9. $db_pwd = 'password';
  10. $database = 'database';
  11. $table = 'table';

  12. if (!mysql_connect($db_host, $db_user, $db_pwd))
  13. die("Can't connect to database");
  14. if (!mysql_select_db($database))
  15. die("Can't select database");
  16. // sending query
  17. $result = mysql_query("SELECT * FROM {$table}");
  18. if (!$result)
  19. {
  20. die("Query to show fields from table failed");
  21. }
  22. $fields_num = mysql_num_fields($result);
  23. echo "<h1>Table: {$table}</h1>";
  24. echo "<table border='1'><tr>";
  25. // printing table headers
  26. for($i=0; $i<$fields_num; $i++)
  27. {
  28. $field = mysql_fetch_field($result);
  29. echo "<td>{$field->name}</td>";
  30. }
  31. echo "</tr>\n";// printing table rows
  32. while($row = mysql_fetch_row($result))
  33. {
  34. echo "<tr>";
  35. // $row is array... foreach( .. ) puts every element
  36. // of $row to $cell variable
  37. foreach($row as $cell)
  38. echo "<td>$cell</td>";
  39. echo "</tr>\n";
  40. }
  41. echo"<p><a href=test.php>Back Home</a></p>";
  42. ?>
  43. </body>
  44. </html>

Comments