简体   繁体   中英

Display only data from table using keyword entered in search box in PHP

I am trying to filter out data from my table using a searchbox in HTML. My search box which should return value from SQL query.

But even if I search, the filtered table is not displayed.

I have checked the 'LIKE' query in phpMyAdmin with '%n' (which I meant an entry in my table ending with 'n' ) and it works, but since in mine I am searching for a specific text that is entered in the search box, I couldn't check for the query that I am using.

Would really appreciate any help and thanks in advance.

 <?php
//error_reporting(E_ERROR | E_PARSE);
$db_host = 'localhost';
$db_user = 'zamil'; // Username
$db_pass = '1234'; // Password
$db_name = 'resi'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());  
}
else{
print("connected");
}
$output = '';
$query = '';

if (isset($_GET['search'])){

$searchq = $_GET['search'];

$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE 'Rep Name' 
LIKE '%$searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = 'There was no entries';
}else{
while ($row = mysqli_fetch_array($query)) {
    $cname = $row['Source of Content'];
    $rname = $row['Rep Name'];

    $output .= '<div>'.cname.' '.rname.'</div>';
    }
  }
}

if ($query != 0) {
die ('SQL Error: ' . mysqli_error($conn));
}

?>

<form action="Sales1.php" method="post"> 
Search: <input type="text" name="search" /> 
<input type="submit" value="Search" /><br />  
</form>

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

</body>
</html>

Your SQL query is incorrect:

SELECT * FROM 'salesflow' WHERE 'Rep Name' LIKE '%$searchq%'

You put single quotes (') around the salesflow table name and Rep Name column name but you should use backticks (`) instead.

For more information see Using backticks around field names .

I think you have entered a wrong query syntax.

$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE
'Rep Name' LIKE '%$searchq%'") or die("could not search!");

It should be written like this:

$query = mysqli_query( $conn, "SELECT * FROM 'salesflow' WHERE
'Rep Name' LIKE '%".$searchq."%'") or die("could not search!");

Always use ' for string in query.

Also, my additional recommendation is not to use SQL for searching in the table, instead, use DataTable based on AngularJS .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM