INTRODUCTION
The search feature is really important nowadays, for searching posts, products, and other things... Today, we will learn how to perform a database search and display the results using PHP.
/!\ Make sure you are using PHP 5.6
THE TUTORIAL
Create a file called dbconnect.php and add the following content into it:
<?php
error_reporting( ~E_DEPRECATED & ~E_NOTICE );
define('DBHOST', 'localhost');
define('DBUSER', 'DB_USERNAME');
define('DBPASS', 'DB_PASSWORD');
define('DBNAME', 'DB_NAME');
$conn = mysqli_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysqli_select_db($conn,DBNAME);
if ( !$conn ) {
die("Connection failed : " . mysqli_error());
}
if ( !$dbcon ) {
die("Database Connection failed : " . mysqli_error());
}
?>
Now, create a file called search.php, and add the following content to it:
<?php
include_once('dbconnect.php');
if(isset($_POST['search'])){
$q = $_POST['q'];
$query = mysqli_query($conn,"SELECT * FROM `table_name` WHERE `thing_to_search` LIKE '%$qname%'");
//Replace table_name with your table name and `thing_to_search` with the column you want to search
$count = mysqli_num_rows($query);
if($count == "0"){
$output = '<h2>No result found!</h2>';
}else{
while($row = mysqli_fetch_array($query)){
$s = $row['column_to_display']; // Replace column_to_display with the column you want the results from
$output .= '<h2>'.$s.'</h2><br>';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<form method="POST" action="search.php">
<input type="text" name="q" placeholder="query">
<input type="submit" name="search" value="Search">
</form>
<?php echo $output; ?>
</body>
</html>
/!\
- Replace table_name with your table name and
thing_to_search
with the column you want to search - Replace column_to_display with the column you want the results from
CONCLUSION
We have created a search feature that will search the database and display the results as
<h2>
paragraphs.
IN THE END
Hope you enjoyed this tutorial, and if it worked for you, give it a thumbs up by clicking the like button.
If you need any more help, you can create a new topic here, and we will be happy to help you!