Advertisement
js95

databasefunctions.php

Oct 23rd, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. <?php
  2.  
  3. /* This file contains several functions to make using databases in PHP easy.
  4. .. Function connectDb lets users easily connect to a database.
  5. .. Function query executes a query on the selected database and returns the result.
  6. .. Function closeConnection closes the connection with the database.
  7. .. Function createTable creates an HTML-table from the results of a query.
  8. */
  9.  
  10. function connectDb($database, $dbhost='localhost', $user='root', $pass='') {
  11. $db = mysqli_connect($dbhost, $user, $pass, $database);
  12. if (mysqli_connect_errno()) {
  13. die('Connection failed: ' . mysqli_error() . ' (' . mysqli_errno() . ')');
  14. }
  15. return $db;
  16. }
  17.  
  18. function query($db, $query) {
  19. mysqli_query($db, $query) or die('Error performing query.');
  20. return mysqli_query($db, $query);
  21. }
  22.  
  23. function closeConnection($db) {
  24. mysqli_close($db);
  25. }
  26.  
  27. function createTable($result, $border=1, $header='Results') {
  28. $buffer = array();
  29. while ($row=mysqli_fetch_assoc($result)){
  30. $buffer[] = $row;
  31. }
  32. echo '<table border="' . $border . '">';
  33. echo "<tr><th colspan=\"100%\">$header</th></tr>";
  34.  
  35. echo '<tr>';
  36. foreach ($buffer[0] as $a => $a_value) {
  37. echo '<td>' . $a . '</td>';
  38. }
  39. echo '</tr>';
  40. foreach ($buffer as $row) {
  41. echo '<tr>';
  42. foreach ($row as $x) {
  43. echo '<td>' . $x . '</td>';
  44. }
  45. echo '</tr>';
  46. }
  47. }
  48.  
  49. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement