Guest User

Untitled

a guest
Jul 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.63 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.   <meta charset='utf-8' />
  5.   <title>Airports demo with PDO Prepared statements</title>
  6. </head>
  7.  
  8. <body>
  9. <h1>Airports demo with PDO Prepared statements</h1>
  10.  
  11.  
  12.  
  13. <?php
  14. //Initialise errors array. This is the array in which catch all the errors, if any, and print them out at the end of the script
  15. $errors = array();
  16.  
  17. echo"<form action='' method='GET'>
  18.     <label for='search'>Search for airports in country</label>
  19.     <input type='text' id='search' name='search' />
  20.     <input type='submit' value='search' />
  21. </form>";
  22.  
  23.  
  24. try{
  25.   //Create a new PDO database connection
  26.   $db = new PDO('sqlite:test.db');
  27.  
  28.   //Set this attribute while testing so PDO doesn't silence error reporting
  29.   $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  30.    
  31.   //Here is the prepared statement
  32.    if(!empty($_GET['search'])){
  33.  
  34.         if($statement = $db->prepare("SELECT name, city, country FROM airports WHERE country = ?")){
  35.  
  36.  
  37.       //The values in this array are bound to the question mark in the prepared SELECT
  38.       $binding = array("{$_GET['search']}%");
  39.      
  40.       $statement -> execute($binding);
  41.      
  42.       //Make sure we get the associative array
  43.       $result = $statement -> fetchall(PDO::FETCH_ASSOC);
  44.      
  45.       //Check for results
  46.       foreach($result as $item => $val){
  47.         echo "<p>{$val['name']} in {$val['city']}</p>";
  48.         }
  49.     }  
  50.  }
  51.  
  52. }
  53. catch(PDOException $e){
  54.   $errors[]=$e->getMessage();
  55. }
  56.  
  57. if(count($errors) > 0){
  58.    echo "<p>Oooops we have errors!</p>";
  59.    echo "<ul>";
  60.    foreach($errors As $error){
  61.       echo "<li>{$error}</li>";
  62.    }
  63.    echo "</ul>";
  64. }
  65.  
  66. ?>
  67.  
  68. </body>
  69. </html>
Add Comment
Please, Sign In to add comment