Thursday, April 24, 2014

Simple search using PHP and Mysql

In this article i am going to explain how to search values using PHP,Mysql.

In this you will learn the following things:

1.$_POST Method
2.Databse Connection
3.Communication between Database and PHP
4.Fetch results from datbase and display.



Functionality Files:

1.Search.php
2.conn.php


Database Connection

   <?php
          $conn=mysqli_connect("localhost","root","","search") or die('Error connection');
        /*Hostname = "localhost".Replace with your hostname*/
         /*Databse Username="root".Replace with your Username*/
         /*Databse Password="".Replace with your Password*/
         /*Databse Name="search".Replace with your database name*/

    ?>

Search.php

     <?php
  $conn=mysqli_connect("localhost","root","","search") or die('Error connection');
  $search_results = '';
  if(isset($_POST['search']))
  {
    $str = $_POST['search'];
    $str = preg_replace("#[^0-9a-z]#i","",$str);
    $query = "SELECT UserName FROM users WHERE UserName LIKE '%$str%'";
    $result = mysqli_query($conn,$query);
    $count = mysqli_num_rows($result);
    if($count>0)
    while($row = mysqli_fetch_array($result))
      {
        $search_results = $search_results."<div>".$row['UserName']."</div>";
      }
  }

?>
    <form action="#" method="post">
      <input type="text" name="search" />
      <input type="submit" value="search"/>
    </form>
    <?php if(isset($_POST['search'])) { ?>
    <h2>Search Results:</h2>
    <?php echo $search_results; ?>
    <?php } ?>
Please share your comments and feedback.Thanks.

No comments:

Post a Comment