Exact value search with PHP - php

I'm using the following code to search the generated table and filter data. My problem is that when I search for lets say 1, it doesn't search & filter only 1 but also the data containing 1 like 11, 21, etc. .
How can I make it search and filter the exact data I enter?
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `tbstats` WHERE CONCAT(`date`, `mode`, `svar`, `sdev`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `tbstats`";
$search_result = filterTable($query);
}
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "dbstats");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="stats_filter.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>Date</th>
<th>Mode</th>
<th>Svar</th>
<th>Sdev</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['mode'];?></td>
<td><?php echo $row['svar'];?></td>
<td><?php echo $row['sdev'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>

When you do LIKE '%".$valueToSearch."%' you search for value that contain %value%.
If you want to search for value that start with your valueToSearch use LIKE '".$valueToSearch."%', for value that end with your valueToSearch use LIKE '%".$valueToSearch."' and for exact value use = '".$valueToSearch."'.
So in your case just replace LIKE '%".$valueToSearch."%' by = '".$valueToSearch."'
Edit :
In your case, you are doing some CONCAT so I guess you want to find the exact value in one of your field, right?
If yes, try to replace :
$query = "SELECT *
FROM `tbstats`
WHERE CONCAT(`date`, `mode`, `svar`, `sdev`) LIKE '%".$valueToSearch."%'";
by
$query = "SELECT *
FROM `tbstats`
WHERE `date` = '".$valueToSearch."'
OR `mode` = '".$valueToSearch."'
OR `svar` = '".$valueToSearch."'
OR `sdev` = '".$valueToSearch."'";
This way you will return data only if your exact searchValue is present inside one or your four field

Currently you concat all your columns to a single string and then search for an occurance of your search string anywhere in this concatenated string.
What you might actually want is to match each column exactly against your search string and return every row, which has an exact match in any column. To do an exact match, don't use LIKE. A simple = is what you want. To combine them, simply use the OR operator.
$query = "SELECT * FROM tbstats WHERE
date = '" . $valueToSearch . "' OR
mode = '" . $valueToSearch . "' OR
svar = '" . $valueToSearch . "' OR
sdev = '" . $valueToSearch . "'";
On top of that, you should realy escape your input or even better, use prepared statements.

Related

how to find correct row or similar row from the mysql if user entered string or keywords into search field?

Below is my PHP code which find the result from mysql table what is typed by user search to search field. It is also finds if user has typed something randomly and find the matching row fetch from the database and show to user. But there is one problem it will fetch the record from the databse as they are sequentially store into the database. but i want is it will show the result which matches the most of the keywords or sentence which is type by user. for example user searching for "search and pagination with php" and all the records are fetch from the database
results:
1. PHP RSS Feed Read and List2.DropDown with Search using jQuery 3.PHP CRUD with Search and Pagination 4.PHP MySQL Date Range Search with jQuery DatePicker"
This is how my code is working. But i want is that result 3rd should be came 1st positon beacuse it matches the greater number of keywords matching and others should also came after that because it have some matching keywords. I have also attached the screenshot of same result screenshot.
If we are searching something in google we are search just randomly. everyone searching type is different but topic is same so google will return the exact result even if type in another way or spelling is typed wrong. How can I do that or what are changes I have to make in code. and If I want to add auto suggestions like google then How can I do that. I want a search field which works like google or StackOverflow for finding the result which has similar or matching results in PHP.
<?php
$conn = mysqli_connect("localhost", "root", "", "blog_samples");
$with_any_one_of = "";
$with_the_exact_of = "";
$without = "";
$starts_with = "";
$search_in = "";
$advance_search_submit = "";
$queryCondition = "";
if(!empty($_POST["search"])) {
$advance_search_submit = $_POST["advance_search_submit"];
foreach($_POST["search"] as $k=>$v){
if(!empty($v)) {
$queryCases = array("with_any_one_of","with_the_exact_of","without","starts_with");
if(in_array($k,$queryCases)) {
if(!empty($queryCondition)) {
$queryCondition .= " AND ";
} else {
$queryCondition .= " WHERE ";
}
}
switch($k) {
case "with_any_one_of":
$with_any_one_of = $v;
$wordsAry = explode(" ", $v);
$wordsCount = count($wordsAry);
for($i=0;$i<$wordsCount;$i++) {
if(!empty($_POST["search"]["search_in"])) {
$queryCondition .= $_POST["search"]["search_in"] . " LIKE '%" . $wordsAry[$i] . "%'";
} else {
$queryCondition .= "title LIKE '" . $wordsAry[$i] . "%' OR description LIKE '" . $wordsAry[$i] . "%'";
}
if($i!=$wordsCount-1) {
$queryCondition .= " OR ";
}
}
break;
}
}
}
}
$orderby = " ORDER BY id desc";
$sql = "SELECT * FROM links " . $queryCondition;
$result = mysqli_query($conn,$sql);
?>
<html>
<head>
<title>Advanced Search using PHP</title>
<script>
function showHideAdvanceSearch() {
if(document.getElementById("advanced-search-box").style.display=="none") {
document.getElementById("advanced-search-box").style.display = "block";
document.getElementById("advance_search_submit").value= "1";
} else {
document.getElementById("advanced-search-box").style.display = "none";
document.getElementById("with_the_exact_of").value= "";
document.getElementById("without").value= "";
document.getElementById("starts_with").value= "";
document.getElementById("search_in").value= "";
document.getElementById("advance_search_submit").value= "";
}
}
</script>
</head>
<body>
<h2>Advanced Search using PHP</h2>
<div>
<form name="frmSearch" method="post" action="index.php">
<input type="hidden" id="advance_search_submit" name="advance_search_submit" value="<?php echo $advance_search_submit; ?>">
<div class="search-box">
<label class="search-label">With Any One of the Words:</label>
<div>
<input type="text" name="search[with_any_one_of]" class="demoInputBox" value="<?php echo $with_any_one_of; ?>" />
</div>
<div>
<input type="submit" name="go" class="btnSearch" value="Search">
</div>
</div>
</form>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<div>
<div><strong><?php echo $row["title"]; ?></strong></div>
<div class="result-description"><?php echo $row["description"]; ?></div>
</div>
<?php } ?>
</div>
</body>
</html>
trial 2
You can compare the results of the search the user inputs and the query results before displaying them. Compare how many words are similar for each result from the array and print the one that has the most first.
$advance_search_submit
$wordsAry[$i]
You could easily use both variables to compare how many words in wordsAry are similar to advance_search_submit and store them in a displayResults array in order of which have more words in common.
Or
Could do the same thing but compare it to the title of the results.
$results
$wordsAry[$i]
Comparing these two variables in a similar way to above. Compare words to result (contains) and save them in order in another array to be displayed.

sql php results and search

I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand

HTML search field always echoeing zero results

So basically I'm thinking that adding a search field to my website is out of my league, but internet has so much information that I decided to give it a go.
I started by adding a form to my index pagina, and this is the code I'm using:
<form method="get" action="search.php">
<table cellpadding="0px" cellspacing="0px">
<tr>
<td style="border-style:solid none solid solid;border-color:#4B7B9F;border-width:1px;">
<input type="text" name="q" style="width:100px; border:0px solid; height:17px; padding:0px 3px; position:relative;">
</td>
<td style="border-style:solid;border-color:#4B7B9F;border-width:1px;">
<input type="submit" value="" style="border-style: none; background: url('images/searchicon.gif') no-repeat; width: 24px; height: 19px;">
</td>
</tr>
</table>
</form>
Next up, my search.php code:
<?php
ini_set('display_errors', 0);
$search = $_GET ['q'];
mysql_connect("localhost", "root", "");
mysql_select_db("release");
$query = mysql_query("SELECT * FROM game WHERE name LIKE '%" . $queryString . "%'");
$foundnum = mysql_num_rows($query);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
echo "$foundnum results found !<p>";
$row = mysql_fetch_assoc($query);
{
echo '<p>'.$row['game_name'].'</p>';
}
}
?>
The query continuously echoes the $foundnum == 0 message even though the data I search for is in the game table.
However, when I try this code:
$query = mysql_query("SELECT game_name FROM game WHERE game_name LIKE '%" . $queryString . "%'");
The query prints '35 results found' on my screen. I have 35 entries in the database, but that doesn't make sense (to me) since I'm searching for one game name which is only entered once...
First of all you are using deprecated version mysql_* need to use mysqli_*. Please check below.
<?php
ini_set('display_errors', 2);
$search = $_GET ['q'];
// see changes from below line
$conn = mysqli_connect("localhost", "root", "","release");
$query = mysqli_query($conn,"SELECT game_name FROM game WHERE game_name LIKE '%". $search ."%'");
$foundnum = mysqli_fetch_array($query);
$count = count($foundnum['game_name']);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
echo "$count results found !<p>";
echo"<pre/>";print_r($foundnum['game_name']);
}
?>
Note:- remove include code from both index and search file that you write on upside.
From your second code it seems like there is a typo.
Try changing $query to
$query = mysql_query("SELECT * FROM game WHERE game_name LIKE '%" . $queryString . "%'");
and let me know if it works or not :)

Get value form same table

I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.

PHP and SQL Server Express to retrieve and show data

I am looking to take a PHP page to retrieve data based on the selection from a drop down list, then show the results based on that selection. I am not even sure where to begin except my connection to the database. I do also know that I have to have a query statement, like I would in SQL, which here is a little bit of that:
$sql = "SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = 'bs1441'";
The bs1441 is just an example of one option that would be in the drop down list. I am not sure what I would put there for it to put in there automatically from the list.
Thanks for the help in advance. Sorry if there is not enough information to go on, but not sure what even would be needed at this point.
EDIT:
This is what I have so far:
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$result = sqlsrv_query( $connection,
'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM Logs
WHERE (ForteID = $ForteID)',
array($ForteID));
while($row = sqlsrv_fetch_array($result))
{
echo($row['ForteID'] . ', '.
$row['Disposition'] . ', '.
$row['appNumber'] . ', '.
$row['Finance_Num'] . ', '.
$row['Num_Payments'] . ', '.
$row['ACH_CC'] . ', '.
$row['Notes'] . ', '.
$row['Date']);
}
sqlsrv_close( $connection);
?>
Then when I look at the page it throws this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\cslogs\getlog.php on line 46
Line 46 is this line:
echo($row['ForteID'] . ', '.
Let me know if that helps!
A couple steps here:
First you need to submit your form with the selection in. I'm not going to go over form submission here but look into it.
once you submit the form you will need to get the value of the drop down and assign it to a variable.
$value= $_POST['value'];
Note: This is a basic example so I didnt add in regex or anything like that.
Once you have your variable ($value) you can then put it in your SQL
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
So here we are processing the query. $dbc is the variable that I chose to represent my database connection and the "or die" part will let me know if the query is valid or not.
Once you have a working query you can then summon the data pulled into an array:
while ($row = mssql_fetch_array($sql)) {
And then you need to assign the results of your query to a variable.
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
The capital words are the titles of the columns in your sql table. After you have them assigned to variables you can do whatever you want to them provided they are inside the while loop.
$value= $_POST['value'];
$sql = mssql_query($dbc,"SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes, Date
FROM cslogs.dbo.Logs
WHERE ForteID = '$value'") or die("Query Error " . mssql_get_last_message());
while ($row = mssql_fetch_array($sql)) {
$result1 = $row["RESULT1"];
$result2 = $row["RESULT2"];
echo $result1;
echo $result2;
}

Categories