mysqli_query fetches empty result - php

On my site, I have 4 radio selectors to add a filter to my search script. If a filter is selected, it should run the search script on only the column which the filter is set to, otherwise if the filter is set to all or not set, it should search all columns. However, when I set my filter to search only one column (the all option works), the query returns an empty result. I have tested the query and it works fine.
I have posted the code for the whole script, however the code block in question is marked with comments. The $filter and $search variables both come through correctly. I have tested this from within the script.
<?php
include ('connect.php');
if(isset($_POST['search'])) {
$search = $_POST['search'];
if(isset($_POST['filter'])) {
$filter = $_POST['filter'];
if($_POST['filter'] == "all") {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
else {
//Code block in question starts
echo "Searching filtered selection only";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
//Code block in question ends
}
}
else {
echo "Searching all";
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes WHERE (model LIKE '%$search%' OR brand LIKE '%$search%' OR type LIKE '%$search%')");
}
}
else {
$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes");
}
while ($row = mysqli_fetch_array($query)) {
echo "<div class='crane'><a href='#!edit' id='" . $row['id'] . "'><img src='images/" . $row['image'] . "' /><p class='craneName'>" . $row['brand'] . ' ' . $row['model'] . "</p></a></div>";
}
?>

$query = mysqli_query($con, "SELECT DISTINCT model, image, brand, id FROM cranes
WHERE '$filter' LIKE '%$search%'") or die(mysqli_error($con));
You’ve put the column name you are passing in $filter in single quotes here, which makes it a mere text literal instead of a column name.
So remove the single quotes … and after that, go read up on SQL injection, but quickly.

Related

How to search for multiple words in database

I cant seem to work out how to search (and display) multiple words that are in my database. This is an image of the database column
There all separate locations: Africa | Wales, UK | Stockholm, Sweden and I want to search for locations that are the same and display them, the following code works if there is one word in the column but not if there are multiple.
<?php
$sessionid = $_SESSION['id'];
$sql = "SELECT * FROM users WHERE id = '$sessionid';";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
$follow = $row['follow'];
$loc = $row['places'];
}
}
$sql = "SELECT * FROM posts WHERE ext LIKE '$loc' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
echo '<div class="posts">';
echo '<img class="img"src='.$row['img'].' width="1500px">';
echo '</div>';
echo '<div class="contain">';
echo '<div class="over">';
echo '<div class="username2">';
echo '<img src="focus.png" width="25px" height="25px" style="padding-right: 10px;">'.''.$row['username'].''.'<img src="loc.png" width="25px" height="25px" style="padding-right: 5px; padding-left: 10px;">'.''.$row['ext'].'';
echo '</div>';
echo '<div class="content">';
echo $row['content'];
echo '</div>';
echo '</div>';
}
}
?>
Also I know this is open to sql injection, it's just a proof of concept. Thanks for the help!!
like operator in mysql comes with wild card e.g. '%', '_' etc.
you can use mysql query like this
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
for example if $loc = 'canada', it will return all the rows which have 'canada' in thier column whether the column contains 'canada, abc' or 'abc, canada'
When using LIKE you should add '%' sign at start and/or at end of LIKE parameter so it won't search for identical term but one starting or ending with the string you provided. Something like:
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
So it will find location that contains your search criteria and not just those identical to it. '%' is replacing any number of characters here.
This goes if you have one search term and you have multiple terms in database column. But if you have multiple search terms you will have to generate your query dynamically, adding one "OR ext LIKE '%$loc%'" for every term.
Use an "%" sign when using the LIKE functionality.
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
This would allow you to search through the content of a field.

SELECT...FROM...WHERE...LIKE issues when combining multiple inputs with multiple columns when selecting output

I am new to PHP programming, and I am working on my first program.. This is for the beginnings of a warehouse management system, so I am needing to be able to query part numbers, EANs, item names, etc. Occasionally, all info will be known, or an exact match when input by the user, but sometimes the user will only know part of an EAN, or want to check all items with a similar name, so the results need to be LIKE the input given by the user.
Everything works okay when the user inputs info in only one input in the form (ex. ONLY the entire or portion of a part number is added to the 'partnumber' input, and it correctly returns relevant rows with the info query'd), but when there are multiple inputs added by the user to query table (ex. user inputs data into 'partnumber' AND 'EAN' input), then the result ends up being every item from the table.. same as 'SELECT * FROM table;'.
Is there a way to query and output data from multiple inputs over multiple columns? I have searched this everywhere, but have yet to find an answer relevant to my need... (or at least one with my level of understanding). Any help in the right direction would be great!
SQL query's I have used so far:
$query = "
SELECT partNumber
, EAN
, UPC
, itemDescription
, SNFlag
, idClass
, idType
FROM productinfo_table
WHERE partNumber LIKE '$partNumber'
OR EAN LIKE '$EAN'
OR itemDescription LIKE '$itemDescription'
OR SNFlag LIKE '$SNFlag'
";
And:
$query = "
SELECT partNumber
, EAN
, UPC
, itemDescription
, SNFlag
, idClass
, idType
FROM productinfo_table
WHERE (partNumber,EAN,itemDescription,SNFlag) IN LIKE ('$partNumber','$EAN','$itemDescription','$SNFlag')";
Among a few others...
testissue.php
<?php //testissue.php
//establish connection
require_once "login.php";
$db_server = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
if(!$db_server) printf('Error connecting to database: %s',mysqli_error($db_server));
//if loop to acquire variables
//if all post array elements are NOT empty
if(!empty($_POST['partNumber']) ||
!empty($_POST['EAN']) ||
!empty($_POST['itemDescription']) ||
!empty($_POST['SNFlag'])) {
//if partNumber is not empty
if(!empty($_POST['partNumber'])) {
$partNumber = '%';
$partNumber .= $_POST['partNumber'];
$partNumber .= '%';
} else {
$partNumber = '';
}
//if EAN is not empty
if(!empty($_POST['EAN'])) {
$EAN = '%';
$EAN .= $_POST['EAN'];
$EAN .= '%';
} else {
$EAN = '';
}
// if itemDescription is not empty
if(!empty($_POST['itemDescription'])) {
$itemDescription = '%';
$itemDescription .= $_POST['itemDescription'];
$itemDescription .= '%';
} else {
$itemDescription = '';
}
//if SNFlag is not empty
if(!empty($_POST['SNFlag'])) {
$SNFlag = '%';
$SNFlag .= $_POST['SNFlag'];
$SNFlag .= '%';
} else {
$SNFlag = '';
}
//echo variables to confirm set, for testing
echo "$partNumber<br/>";
echo "$EAN<br/>";
echo "$itemDescription<br/>";
echo "$SNFlag<br/>";
//query to pull data to insert into table rows
//$query = "SELECT partNumber,EAN,UPC,itemDescription,SNFlag,idClass,idType FROM productinfo_table WHERE partNumber LIKE '$partNumber' OR EAN LIKE '$EAN' OR itemDescription LIKE '$itemDescription' OR SNFlag LIKE '$SNFlag'";
$query = "SELECT partNumber,EAN,UPC,itemDescription,SNFlag,idClass,idType FROM productinfo_table WHERE (partNumber,EAN,itemDescription,SNFlag) IN LIKE ('$partNumber','$EAN','$itemDescription','$SNFlag')";
$result = mysqli_query($db_server,$query);
if(!$result) printf("Error querying database: %s",mysqli_error($db_server));
$rows = mysqli_num_rows($result);
}
//if all post array elements ARE empty
else {
echo "empty post array";
$rows = '';
}
//echo form input
echo <<<HERE
<pre>
<form action='testissue.php' method='post'>
Part No. <input type='text' name='partNumber' />
EAN <input type='text' name='EAN' />
Item Desc. <input type='text' name='itemDescription' />
SN Flag <input type='text' name='SNFlag' />
<input type='submit' value='Search' />
</form>
</pre>
HERE;
//print post array to confirm set values, for testing
echo "<br/>";
print_r($_POST);
echo "<br/><br/>";
//echo table for output
echo <<<HERE
<table>
<tr><th>Part No.</th> <th>EAN</th> <th>UPC</th> <th>Item Desc.</th> <th>SN Flag</th> <th>Class ID</th> <th>Type ID</th></tr>
HERE;
// for loop function to populate items in table
for($a=0;$a<$rows;++$a){
echo "<tr>";
$col = mysqli_fetch_row($result);
for($b=0;$b<7;++$b) echo "<td>$col[$b]</td>";
echo "</tr>";
}
echo "</table>";
//close connection
mysqli_close($db_server);
?>
Please let me know if you need anything else to help or offer any improvements.
Thanks a lot!
You need to use AND clause rather than OR.
AND will give you rows that match all conditions in WHERE clause
OR will return rows that match any of the conditions in WHERE clause
$query = "
SELECT partNumber
, EAN
, UPC
, itemDescription
, SNFlag
, idClass
, idType
FROM productinfo_table
WHERE partNumber LIKE '$partNumber'
AND EAN LIKE '$EAN'
AND itemDescription LIKE '$itemDescription'
AND SNFlag LIKE '$SNFlag'
";
Note: Please note the suggestions provided in the comments to prevent SQL injection
$sql="SELECT *FROM table where partNumber = '$partnumber'order by id ASC";

PHP string compare and search in a multiple table column

its my first post and I have a problem with a PHP search.
Here,
$searchq = $_POST['searchq'];
so far when a single word is supplied for searchq like naresh, google, lamgade then it search in a db but when there is a multiple search like
naresh lamgade at a same time then there is error for these word because it only search in a first_name column and what i want to search naresh in a first_name column and lamgade in a last_name column
Here is the code
<pre> $searchq = $_POST['searchq'];
$conn = mysqli_connect('localhost','root','','std_info') or die("Cant' Connect to db");
$query = mysqli_query($conn,"select * from student_details where first_name like '%$searchq%' or last_name like '%$searchq%'");
$count = mysqli_num_rows($query);
if($count == 0) {
echo "<br>";
echo "Can't find, try entering only first name or last name";
}
else {
do something`</pre>
}
The problem is
In a search bar, when i try entering naresh lamgade and search then
searchq =naresh+lamgade
and it search in both first_name and last_name column with a naresh+lamgade so there is no result.
I want to know , how to break these two words and search in a different column with these words.
The problem is
In a search bar, when i try entering naresh lamgade and search then
searchq =naresh+lamgade"
I guess that you put the textfield inside a form without method="post".
If you did, try like this in searchq:
... WHERE first_name LIKE "'%'.$searchq.'%'" or last_name like "'%'.$searchq.'%');
Use explode to split query.
Also your code is dangerous. Use mysqli_escape_real_string to escape special characters in a query:
<?php
$searchq = explode(" ", $_POST['searchq']);
$conn = mysqli_connect('localhost', 'root', '', 'std_info') or die("Cant' Connect to db");
$query = mysqli_query($conn, "select * from student_details where (first_name like '%" . mysqli_real_escape_string($searchq[0]) . "%' OR first_name like '%" . mysqli_real_escape_string($searchq[1]) . "%') OR (last_name like '%" . mysqli_real_escape_string($searchq[1]) . "%' OR last_name like '%" . mysqli_real_escape_string($searchq[0]) . "%'");
$count = mysqli_num_rows($query);
if ($count == 0)
{
echo "
";
echo "Can't find, try entering only first name or last name";
}
else
{
do something`
Thanks everyone for the answer but I have used this query and it's working perfectly as I wanted.
$query = mysqli_query($conn, "SELECT * FROM student_details WHERE CONCAT(first_name,' ',last_name) like '%$searchq%'");

Rewrite query depending on GET parameters

I'm working on a search engine on my website. Users can add on criteria which is submitted with a GET in the url.
When users select for example 1 criteria, it looks like this:
localhost/search.php?course=1&price=&name=
They have 3 criteria they can select, so as you see he only selected COURSE.
Now I have to select from the database according to the criteria so my code looks like this:
if ($_GET['price'] > 0 && $_GET['name'])
{
$search_price = $_GET['price'];
$search_name = $_GET['name'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price AND name LIKE '%$search_name%'");
}
elseif ($_GET['price'] > 0)
{
$search_price = $_GET['price'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND price < $search_price");
}
elseif ($_GET['name'])
{
$search_name = $_GET['name'];
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id' AND name LIKE '%$search_name%'");
}
else
{
$result2 = mysql_query("SELECT id, name, price, views, userid, type, anonymous FROM files WHERE course='$course_id'");
}
while ($row2 = mysql_fetch_assoc($result2))
{
.....
But this can not be the correct way, because if eventually users can select 10 criteria this is going to be a very long code
How do I fix this?
What I would do is dynamically create the sql query,and then execute it at the end. So something like this
$query_string = "SELECT blahblah, blahblah, blah blah from blahx where 1=1 ";
$where = "";
if(isset($_GET['somecriteria']))
{
$where .= " AND blahblah = $_GET['somecriteia'] ";
}
if(isset($_GET['someOTHERcriteria']))
{
$where .= " AND blahblah=$_GET['someOTHERcritera'] ";
}
mysql_query($query_string . $where);
etc..
Take note this is just to show you how to achieve your objective. This is obviously prone to SQL Injection attacks and you'd have to clean the stuff up.
Use $_post to send larger amounts of information to the php script. When using get you should create the url to include get calls only if they are populated. As such if no price is selected the url should not include "price=". This will cause problems with your receiving script.
Your database script can be done with one call including only the selected criteria.
Myqsl has been depreciated, you need to look into Myqsli or PDO

A way to skip over a row if it has already been displayed

I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.

Categories