search.php

Source of search.php

<!DOCTYPE html>
<html lang = "en-US"> 

  <head>
    <meta charset = "UTF-8">
    <title>search.php</title>
  </head>
  <body>
    <h1>My Contacts</h1>
  <?php
    try {
      $fieldName = array("contactID", "name", "company", "email");
      //get values from form
      
      $srchField = filter_input(INPUT_POST, "srchField");
      $srchValue = filter_input(INPUT_POST, "srchVal");
      
      //don't proceed unless it's a valid field name
      if (in_array($srchField, $fieldName)){
        $field = $srchField;
        //put value inside %% structure
        $value = "%$srchValue%";
        
        $con= new PDO('mysql:host=localhost;dbname=db', "user", "pwd");
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $stmt = $con->prepare("SELECT * FROM contact WHERE $field LIKE ?");
        $stmt->execute(array($value));
        
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($result)){
          print "No matches found";
        } else {
          foreach($result as $row){
            foreach ($row as $field => $value){
              print "<strong>$field:</strong> $value <br />";
            } // end field loop
            print "<br />";
          } // end row loop
        } // end 'empty results' if
        
      } else {
        print "That is not a valid field name";
      } // end if
    } catch(PDOException $e) {
      echo 'ERROR: ' . $e->getMessage();
    } // end try
  ?>
  </body>
</html>