Monday, March 27, 2017

Multiple Tables Search in PHP PDO

Simple Multiple Tables Search in PHP  PDO

This is a  Simple Multiple Tables Search in PHP  PDO .

  • First Create A Database called "multitable" in phpmyadmin.
  • After Creating Database in phpmyadmin create table called 'searchkeyword','posts' .
  • Add Column's on searchkeyword as sid and set as autoincrement ,searchkeyword and set as varchar.
  • Then Add Column's on posts as post_id and set as autoincrement ,post_title,post_content and set as varchar, and sid as integer.
  • And last of database section insert some values on table columns and keep sid of searchkeyword table=posts table.

Now Lets Start For Codding For Multiple Table Search in PHP  PDO

  • First You need to connect with Datebase 'Connection in PDO'.
  1. <?php
  2.     $host = "localhost";
  3.     $user = "root";
  4.     $password = "";
  5.     $database_name = "multitable";
  6.     $dbcon = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
  7.     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  8.     ));
  9.     ?>
  • Now Create Simple HTML form As This Below;
  1.    <form  action="index.php" method="post">
  2.    
  3.       <input type="text" placeholder="Search" name="searchkeyword">
  4.      
  5.     <input type="submit"  name="submit" value="submit">
  6.   
  7.   </form>   
  • AT Last This Scripts is for multiple table search process in pdo
  1.  <?php
  2.     if(isset($_POST['submit'])){
  3.         ?>
  4.    <?php
  5. $keyword=$_POST['searchkeyword'];
  6. // Query For Multiple Tables Search ( LIMIT 0 , 10) This Limit  shows upto Ten records
  7. $query = $dbcon->prepare("select c.* , p.* from searchkeyword c,posts p where searchkeyword LIKE '%$keyword%'  AND c.sid= p.sid LIMIT 0 , 10");
  8. $query->bindValue(1, "%$keyword%", PDO::PARAM_STR);
  9. $query->execute();
  10. $strong_keyword = '<strong>'.$keyword.'</strong>';
  11. // Display search result Here
  12.          if (!$query->rowCount() == 0) {
  13.                  echo " &nbsp;&nbsp;&nbsp;&nbsp;Search found :<br/>";            
  14.             while ($results = $query->fetch()) {                
  15.                 ?>             
  16.              
  17.               <?php    echo '<h1>'.str_ireplace($keyword,$strong_keyword,$results['post_title']).'</h1>'; ?><br />
  18.                 <?php    echo '<h3>'.str_ireplace($keyword,$strong_keyword,$results['post_content']).'</h3>'; ?>
  19.                
  20.                                 
  21.        <?php      }
  22.                     
  23.         } else {?>
  24.         
  25.          <?php    echo 'Nothing found'; ?>
  26.         <?php }
  27.     
  28.     ?>
  29.  
  30.         <?php 
  31.     }
  32.     ?>
                  Note: Save All This Scripts in  index.php file..  

No comments:

Post a Comment