How to perform a database search and display the results in PHP


#1

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 = mysql_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 = '

No result found!

'; }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 .= '

'.$s.'


'; } } } ?> Search <?php echo $output; ?> ```

/!\

  1. Replace table_name with your table name and thing_to_search with the column you want to search
  2. 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 `

` 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!


Mysqli_fetch_all wont work (PHP/mysql)