Advertisement
jraavis

PHP: Search by ID

Apr 12th, 2020
748
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.63 KB | None | 0 0
  1. <?php
  2.     /* These are usefull to show all errors */
  3.     error_reporting(E_ALL);
  4.     ini_set('display_errors', 1);
  5.     /* /These are usefull to show all errors */
  6.  
  7.     $db_host = '127.0.0.1';
  8.     $db_user = 'root';
  9.     $db_pass = 'root';
  10.     $db_name = 'college';
  11.     $tb_name = 'students';
  12.     $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
  13.     if($conn === false){
  14.         die('Error while connecting:' . mysqli_connect_error());
  15.     }
  16.     $post = $_POST;
  17.     $columns = array('id'=>'ID', 'first_name'=>'First Name', 'last_name'=>'Last Name', 'email'=>'E-Mail');
  18.     if( isset($post) && isset($post['id']) && $post['id'] != '' ) {
  19.         $sql_query = "SELECT * FROM $tb_name WHERE $id = '" . $post['id'] . "'";
  20.         if($result = mysqli_query($conn, $sql_query)){
  21.             if(mysqli_num_rows($result) > 0){
  22.                 echo "<table>";
  23.                 echo "<tr>";
  24.                 foreach($columns as $column) {
  25.                     echo "<th>$column</th>";
  26.                 }
  27.                 echo "</tr>";
  28.  
  29.                 while($row = mysqli_fetch_array($result)){
  30.                     echo "<tr>";
  31.                         echo "<td>" . $row['id'] . "</td>";
  32.                         echo "<td>" . $row['first_name'] . "</td>";
  33.                         echo "<td>" . $row['last_name'] . "</td>";
  34.                         echo "<td>" . $row['email'] . "</td>";
  35.                     echo "</tr>";
  36.                 }
  37.                 echo "</table>";
  38.                 mysqli_free_result($result);
  39.             } else {
  40.                 echo "Sorry! No records found.";
  41.             }
  42.         } else {
  43.             echo "Error while executing $sql_query. " . mysqli_error($conn);
  44.         }
  45.      
  46.         // Close connection
  47.         mysqli_close($conn);
  48.     } else {
  49.         echo "Sorry! Invalid ID entered/selected";
  50.     }
  51.    
  52. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement