Advertisement
callmewhateverUwant

select data from database PDO

Jun 5th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. <?php
  2. echo "<table style='border: solid 1px black;'>";
  3. echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
  4.  
  5. class TableRows extends RecursiveIteratorIterator {
  6. function __construct($it) {
  7. parent::__construct($it, self::LEAVES_ONLY);
  8. }
  9.  
  10. function current() {
  11. return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
  12. }
  13.  
  14. function beginChildren() {
  15. echo "<tr>";
  16. }
  17.  
  18. function endChildren() {
  19. echo "</tr>" . "\n";
  20. }
  21. }
  22.  
  23. $servername = "localhost";
  24. $username = "username";
  25. $password = "password";
  26. $dbname = "myDBPDO";
  27.  
  28. try {
  29. $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  30. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  31. $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
  32. $stmt->execute();
  33.  
  34. // set the resulting array to associative
  35. $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  36. foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
  37. echo $v;
  38. }
  39. }
  40. catch(PDOException $e) {
  41. echo "Error: " . $e->getMessage();
  42. }
  43. $conn = null;
  44. echo "</table>";
  45. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement