Guest User

Untitled

a guest
Nov 29th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. <?php
  2. $db_host = "localhost";
  3. $db_name = "your_database_name";
  4. $db_user = "your_database_user";
  5. $db_pass = "your_database_pass";
  6.  
  7. /* function to run a SQL query using PDO connection to MySQL db */
  8. function sql($s,$v=array()){
  9. global $db_host, $db_name, $db_user, $db_pass;
  10. $dbh = new PDO("mysql:host=$db_host;dbname=$db_name",$db_user,$db_pass);
  11. if (!$dbh) die("Could not connect to database");
  12. $stmt = $dbh->prepare($s);
  13. if (!$stmt) die("Prepare failed");
  14. foreach($v as $key => $val) $bind = $stmt->bindValue($key,strval($val));
  15. $exec = $stmt->execute();
  16. if (!$exec) die("Execute failed");
  17. $dbh = null;
  18. return $stmt;
  19. }
  20.  
  21. /* function to print out a record set as an HTML table */
  22. function html_table($s){
  23. echo "<table border=1><tr>";
  24. for($i=0;$i<$s->columnCount();$i++) echo "<th>".$s->getColumnMeta($i)["name"]."</th>";
  25. echo "</tr>";
  26. while($r=$s->fetch(PDO::FETCH_ASSOC)) {
  27. echo "<tr>";
  28. foreach($r as $val) echo "<td>$val</td>";
  29. echo "</tr>";
  30. }
  31. echo "<table>";
  32. }
  33. ?>
  34. <!DOCTYPE html>
  35. <html>
  36. <body>
  37. <?php
  38. /* create a table */
  39. $q = "create table tbl_users (usr_id int, usr_name varchar(16))";
  40. $s = sql($q);
  41.  
  42. /* insert a record */
  43. $q = "insert into tbl_users (usr_id, usr_name) values (:b_id, :b_nme)";
  44. $s = sql($q, array(":b_id"=>1,":b_nme"=>"John Smith"));
  45.  
  46. /* print the table */
  47. $q = "select * from tbl_users";
  48. $s = sql($q);
  49. html_table($s);
  50.  
  51. /* drop the table */
  52. $q = "drop table tbl_users";
  53. $q = sql($q);
  54. ?>
  55. </body>
  56. </html>
Add Comment
Please, Sign In to add comment