how to make a search form to search a record from list in php code example

Example 1: php sql search form

<?php
$localhost = "localhost";
$username = "root";
$password = "";
$dbname = "samueldb";
$con = new mysqli($localhost, $username, $password, $dbname);
if( $con->connect_error){
    die('Error: ' . $con->connect_error);
}
$sql = "SELECT * FROM users";
if( isset($_GET['search']) ){
    $name = mysqli_real_escape_string($con, htmlspecialchars($_GET['search']));
    $sql = "SELECT * FROM users WHERE firstname ='$name'";
}
$result = $con->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Search form using mysqli</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<label>Search</label>
<form action="" method="GET">
<input type="text" placeholder="Type the name here" name="search"> 
<input type="submit" value="Search" name="btn" class="btn btn-sm btn-primary">
</form>
<h2>List of students</h2>
<table class="table table-striped table-responsive">
<tr>
<th>ID</th>
<th>First name</th>
<th>Lastname</th>
<th>Address</th>
<th>Contact</th>
</tr>
<?php
while($row = $result->fetch_assoc()){
    ?>
    <tr>
    <td><?php echo $row['user_id']; ?></td>
    <td><?php echo $row['firstname']; ?></td>
    <td><?php echo $row['lastname']; ?></td>
    <td><?php echo $row['address']; ?></td>
    <td><?php echo $row['contact']; ?></td>
    </tr>
    <?php
}
?>
</table>
</div>
</body>
</html>

Example 2: search function in php

<?php
mysql_connect("localhost","root","") or die("could not connect");
mysql_select_db("kkp") or die("could not find db!");
$output ='';

//collect
if (isset($_POST['search'])){
    $searchq = $_POST['search'];
    $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
    $query = mysql_query("SELECT * FROM personal_info WHERE FirstName LIKE '%$searchq%' OR SurName LIKE '%$searchq%'") or die("could not search");
    $count = mysql_num_rows($query);
    if($count == 0){
        $output = 'There was no search results!';
    }else{
        while($row = mysql_fetch_array($query)){
            $fname = $row['FirstName'];
            $lname = $row['SurName'];
            $id = $row['id'];

            $output .= '<div>'.$fname.''.$lname.'</div>';
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Search</title>
</head>
<body>
    <form method="post" action="search.php"></form>
        <input type="text" name="search" placeholder="Search for student">
        <input type="submit" value="Submit">
</body>
</html>

<?php print("$output");?>

Tags:

Php Example