I setup a php file to pull data from a database, and list that on a table. I then made a simple search function to search that data, however I can't figure out how to implement a space when searching. For example, if I searched test 2 (test from one column, 2 from another) it won't display anything. However, if I were to search 'test2' or '2test' it displays all results. How would I implement that space into my code?
Here's my code:
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `master` WHERE CONCAT_WS(`id`, `office`, `firstName`, `lastName`, `type`, `status`, `deadline`, `contactPref`, `email`, `phoneNumber`, `taxPro`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `master`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "", "", "");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
echo "test";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="Untitled-1.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<table>
<tr>
<th>ID</th>
<th>Office</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
<th>Status</th>
<th>Deadline</th>
<th>Contact Preference</th>
<th>Email</th>
<th>Phone Number</th>
<th>Tax Pro</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['office'];?></td>
<td><?php echo $row['firstName'];?></td>
<td><?php echo $row['lastName'];?></td>
<td><?php echo $row['type'];?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['deadline'];?></td>
<td><?php echo $row['contactPref'];?></td>
<td><?php echo $row['email'];?></td>
<td><?php echo $row['phoneNumber'];?></td>
<td><?php echo $row['taxPro'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>```
A way to do this could be to have your string spillted up into words in php. You could use explode function for this (https://www.php.net/manual/en/function.explode.php)
And then write SQL where clause like this (im assuming you are using mysql):
WHERE col LIKE %word% OR col LIKE %word2%
This would be a bit inefficient, maybe the tool what you are looking for is elasticsearch? https://www.elastic.co/what-is/elasticsearch
Also, you should NEVER use . operator on an untrusted input. Because it creates MySQL Injection vulnerability. See this question for reference: How can I prevent SQL injection in PHP?
The simplest solution would be using FULLTEXT index in your mysql field. But I don't recommend using it on production. Instead, for actual projects external searching engine must be considered (e.g. Elasticsearch, etc.)
Related
I am trying to query a database and display the results. The query is based on information from an html form. However, when I enter a name such as john in the form, for which the table has 2 entries with that name, I get 0 results. I don't know what the problem is.
Here is the html form:
<form action="cust_details_search.php" method="post">
Name :
<input type="text" name="name_search" id="name_search" >
Email :
<input type="email" name="email_search" id ="email_search" >
Phone no. :
<input type="phone" name="phone_search" id="phone_search" >
Address :
<input type="text" name="address_search" id="address_search" >
City :
<input type="text" name="city_search" id="city_search" >
State :
<input type="text" name="state_search" id="state_search" >
<br> <br>
Country :
<input type="text" name="country_search" id="country_search">
Product Enquired for :
<input type="text" name="prod_search" id="prod_search">
<input type="submit" value="Submit">
</form>
And the php file:
<?php
$server = "127.0.0.1";
$dbUsername = "root";
$dbPassword = "";
//create connection
$dbconn = new mysqli($server, $dbUsername, $dbPassword, $dbname);
$name_search = $_POST['name_search'];
$email_search = $_POST['email_search'];
$phone_search = $_POST['phone_search'];
$address_search = $_POST['address_search'];
$city_search = $_POST['city_search'];
$state_search = $_POST['state_search'];
$country_search = $_POST['country_search'];
$prod_search = $_POST['prod_search'];
$run_query = mysqli_query($dbconn,
"SELECT *
FROM CustomerDetails
WHERE (Name LIKE '%.$name_search.%')
OR (`Phone no.` LIKE '%.$phone_search.%')
OR (`Address` LIKE '%.$address_search.%')
OR (`City` LIKE '%.$city_search.%')
OR (`State` LIKE '%.$state_search.%')
OR (`Country` LIKE '%.$country_search.%')
OR (`Product Enq. For` LIKE '%.$prod_search.%')
OR (`Email` LIKE '%.$email_search.%')");
?>
<html>
<head>
<title>Search Resutls</title>
<style>
body {
background-color: rgb(131,41,54);
}
h1 { color:#FFFFFF
}
h2 { color:#FFFFFF
}
p { color:#FFFFFF
}
</style>
</head>
<body>
<center>
<h2> Customer Details </h2>
<table style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone no. </th>
<th>Address </th>
<th>City </th>
<th>State </th>
<th>Country</th>
<th>Product Enquired for </th>
<th>Follow up details </th>
</tr>
</thead>
<tbody>
<?php
while($result = mysqli_fetch_assoc($run_query)) {
?>
<tr>
<td><?php echo $result['Name'] ?> </td>
<td><?php echo $result['Email'] ?></td>
<td><?php echo $result['Phone no.'] ?></td>
<td><?php echo $result['Address'] ?></td>
<td><?php echo $result['City'] ?></td>
<td><?php echo $result['State'] ?></td>
<td><?php echo $result['Country'] ?></td>
<td><?php echo $result['Product Enq. For'] ?></td>
<td><?php echo $result['Follow Up'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</center>
</body>
</html>
Any help is appreciated. Thank you in advance!
You are using the PHP concatenator . but you dont need to in a double quoted string. $variables are automatically expanded in a double quoted string so try
$run_query = mysqli_query($dbconn,
"SELECT *
FROM CustomerDetails
WHERE (Name LIKE '%$name_search%')
OR (`Phone no` LIKE '%$phone_search%')
OR (`Address` LIKE '%$address_search%')
OR (`City` LIKE '%$city_search%')
OR (`State` LIKE '%$state_search%')
OR (`Country` LIKE '%$country_search%')
OR (`Product Enq For` LIKE '%$prod_search%')
OR (`Email` LIKE '%$email_search%')");
ALso some of your column names had a . in them? I assume these column names do not actually contain dots. However if the do, I suggest you remove them by editing your schema.
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
I'm having trouble getting my php search project working properly, having followed a guide, I don't fully understand the guide/code. My search bar will allow me to search for jobs in the database, but currently it shows all jobs and filters the one you search.
Is it possible to display these jobs as links, where it will take you to another page and display the currently selected job.
Here is my current code:
<?php
require 'config.php';
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="submit" value="Search"><br><br>
<table>
<tr>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['budget'];?></td>
<td><?php echo $row['duedate'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Your problem is this line:
if(isset($_POST['search']))
There's no variable called "search" which will be submitted by your form, so its value will never be set, and this if block will never be entered. I suspect you've confused the "name" attribute which determines the variable's name in the POST array, with its value ("Search", in the case of your button). Try
if(isset($_POST['submit']))
instead.
See also my comments above about your security problems and aim to fix those a.s.a.p.
I have a sample code for my problem. what i want to do is if i search for "Helloworld" then i want to inform the user that there's no data matched based from their inputted data. Im thinking if can i use if else statement to do a validation if the data inputted didn't matched any rows and if the inputted data matched some rows. As i visualized the solution for this problem i think this method is the solution but i don't how can i do this. i think the solution is to put if else condition here's my code how i thought about it
if the result of search is not nothing then it will show the result then if nothing then the message will appear "no data matched"
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="search" value="Filter"><br><br>
<?php
if($result_validation != ''){
?>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['fname'];?></td>
<td><?php echo $row['lname'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php endwhile;?>
</table>
<?php
}else{
echo "no data matched";
}
?>
</form>
</body>
</html>
I see no point in displaying the entire table inside the form, you should display it somewhere outside of the form. Having said that, $result_validation variable is undefined, you need to use $search_result in your code.
And as per your question, use mysqli_result::$num_rows to check number of rows returned from the SELECT query.
if($search_result->num_rows){
// display table
}else{
echo 'no data matched';
}
Here is my php code with html text box
<input type="text" class="form-control" value="<?php
$items=mysql_query("select * from order_detail_master where order_id = ".$no_of_orders['order_id']);
echo "<table><tr><th>Item Name</th><th>Qty</th></tr>";
if($items){
while($res_items = mysql_fetch_assoc($items)){
$item_name = mysql_query("select item_name from item_master where item_id = ".$res_items['item_id']);
while($item_name_rs = mysql_fetch_assoc($item_name)){
$i_n = $item_name_rs['item_name'];
}
echo "<tr><td>".$i_n."</td><td>".$res_items['odm_quantity']."</td></tr>";
}
}
echo "";
And my output look like
I'm not sure what it is you are trying to do either but I see no reason to have an html input type when it's not actually a form. If all you are doing is trying to query the database, I put this simple script together that might help guide you along the lines of what you are attempting to achieve. You can use * as a wild card in your mysql query line to help simplify things. Also, make sure $link matches your db_connect. I have not tested this but it should work fine.
<?php
$sql=mysqli_query($link, "select * FROM order_detail_master") or die(mysqli_error($link));
?>
<tr>
<th>Order ID</th>
<th>Item ID</th>
<th>Item Name</th>
<th>ODM Quantity</th>
</tr>
<?php
while($row=mysqli_fetch_assoc($sql))
{
?>
<tr>
<td><?php echo $row['order_id'];?></td>
<td><?php echo $row['item_id'];?></td>
<td><?php echo $row['item_name'];?></td>
<td><?php echo $row['odm_quantity'];?></td>
</tr>
<?php
}
?>
This is my first posting in SO, my apologize if I opened an existing question. As I couldn't find the result in Google. Sorry to said but I'm still fresh in PHP PDO and in learning stage.
Back to my question, currently I'm building a customer visit logs from my wife but I'm stuck with the result. I have two table which one stores the customer information and another table store the visit details. I uploaded the test table at here: SQL Fiddle
And below is my current coding and I'm using PHP PDO while
<?php
require_once 'dbconnect.php';
$p_id = $_GET['name'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT customer.fname, customer.lname, customer.gender, services.treatment, services.date
FROM customer LEFT JOIN services
ON customer.id = services.customer_id
WHERE customer.slug LIKE :id";
$q = $conn->prepare($sql);
$q->execute(array('id' => $p_id));
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">
<h1>Customer Record</h1>
Name: <br />
Gender: <br />
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Gender</th>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname'])?></td>
<td><?php echo htmlspecialchars($r['gender']); ?></td>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
Seach Again
</body>
</div>
</html>
And I achieve as what SQL Fiddle result, but what I wanted is, the name and gender is not keep repeating.
I attached together with the screenshot:
Screenshot
What I want is as per the screenshot image, Name: John Doe and Gender: Male, should be on top and not keep on repeating while the table below show all the visit details. I tried to modified the code but it seems it don't really work out.
Please advise me as I'm really out of idea how to achieve what I want.
Thank you so much.
Since you do a LEFT JOIN in your SQL query, you know ahead of time that all of the fname, lname and gender values returned by $q->fetch() are going to be for the same customer.slug, right? So you can count on that.
My suggestion would be to instead use the fetchAll() function to get an array of all records for customer.slug, and then render that in your view. For example (haven't tested this) you could add the following after $q->setFetchMode(PDO::FETCH_ASSOC); ...
$cs = $q->fetchAll(); // customer services join
Then, in your <html> view, you could do something like the following:
<h1>Customer Record</h1>
Name: <?php echo htmlspecialchars($cs[0]['fname'].' '.$cs[0]['lname']); ?> <br />
Gender: <?php echo htmlspecialchars($cs[0]['gender']); ?> <br />
<table>
<thead>
<tr>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach($cs as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
Of course, it might also be a good idea to check to see that any records were returned by your query and display a "not found" message if not. After all, $cs[0] might be empty, giving you a PHP error.