i've a problem with a search form. It works only if I use all the 4 fields, but if a leave a field empty the while loop echoes out all the table's records.
Can someone please help me?
This is my php code for the search function
<?php
if (isset($_POST['cerca'])){
$cerca_tt = $_POST['tt_carrier'];
$cerca_risorsa = $_POST['risorsa_cerca'];
$cerca_team = $_POST['team_cerca'];
$cerca_linea = $_POST['linea_cerca'];
$sql_cerca = "SELECT * FROM normal WHERE
tt LIKE '%".$cerca_tt."%'
OR risorsa LIKE '%".$cerca_risorsa."%'
OR team LIKE '%".$cerca_team."%'
OR linea LIKE '%".$cerca_linea."%'";
if($sql_cerca) {
$trovati = mysql_query($sql_cerca); ?>
if the POST is blank then the variable is blank thus everything will match like '%%'
for example if $cerca_tt is blank. your query would be
"SELECT * FROM normal WHERE tt like '%%'"
that matches everything.
create the query based on the POST response.
$sel = "SELECT * from normal";
//You will need to deal with the WHERE part of the query.
if (!empty($cerca_tt)){
$sel .= " OR tt like '%".$cerca_tt."'";
}
etc....///
If you only provide one search parameter and the rest are empty strings, which you wrap with %, you are effectively searching everything. You need to build up your query. For example (simple):
$sqlParts = [];
if(isset($_POST['tt_carrier'])) {
$sqlParts[] = "tt LIKE '%".$cerca_tt."%'";
}
if(isset($_POST['risorsa_cerca'])) {
$sqlParts[] = "risorsa LIKE '%".$cerca_risorsa."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "team LIKE '%".$cerca_team."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "linea LIKE '%".$linea_cerca."%'";
}
if(!empty($sqlParts)) {
$sql = "SELECT * FROM normal WHERE " . implode(' OR ', $sqlParts);
}
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
I want to create code to filter my catagory and tag, I'm using select box to filter, my code like this:
if ($filter2) {
$addedCondition = " AND (nama_kat LIKE '%$filter2%' OR nama_tag LIKE '%$filter2%') ";
}
$query = $db->prepare("SELECT * FROM konten
WHERE (nama_kat LIKE '%$filter1%'
OR nama_tag LIKE '%$filter2%') ".$addedCondition."
ORDER BY 'date' DESC");
work if I'm only filter one word, but once I filter with two words it's not working, my web displaying all articles.
you can try filter here http://stanime.pe.hu/
You have to explode your string into words and use OR.
$addedCondition = '';
$filter2 = explode(' ',$filter2);
foreach($filter2 as $word)
{
$addedCondition .= " OR (nama_kat LIKE '%$word%' OR nama_tag LIKE '%$word%') ";
}
My question is fairly simple. I have a column in my table labeled 'area' that appears like:
ma_south-coast
ma_south-caost
ma_north
ca_los-angelos
ca_los-angelos
I want to be able to select just the 'ma' ones. I am trying to do something such as:
$res_area = mysqli_query($connection,"select area from users");
while ($row_state = mysqli_fetch_array($res_area)) {
$state_exp = reset(explode("_", $row_state['area']));
}
Printing $state_exp at this point would give me: mamamacaca which is good. But I want to filter so I only get the ma ones.
You can extend your query with WHERE column LIKE "ma%" or check with substr($row_state['area],0,2) if the first two characters are "ma".
You could try this:
$res_area = mysqli_query($connection,"select area from users");
while ($row_state = mysqli_fetch_array($res_area)) {
$state_exp = stristr(reset(explode("_", $row_state['area'])),'ma');
}
You're looking for the LIKE operator. The LIKE operator is used to search for a specified pattern in a column.
Try this:
SELECT * FROM tablename WHERE areaLIKE 'ma_%';
You can read more about the LIKE operator here.
The optimal solution could be :-
$res_area = mysqli_query($connection,"select area from users WHERE area LIKE 'ma_*')";
while ($row_state = mysqli_fetch_array($res_area)) {
if(stripos(reset(explode("_", $row_state['area'])),'ma') !== FALSE)
{
$state_exp = reset(explode("_", $row_state['area']));
}
}
I have a search form with a possible 15 or so fields, however not all are required to carry out a search, for instance;
a user might search for a registered user in 'London' who works in 'Finance' but leave all other fields blank, such as $availability or $salary etc, so $_POST data may look something like:
$location = $_POST['location']; // Value - London
$sector = $_POST['sector']; // Value - Finance
$available = $_POST['available']; // Value - Any
$salary = $_POST['salary']; // Value - Any
Bearing in mind I may have another 12 or so 'Any' values from other fields, what is the best way to query the database (PHP/MySQL) to return results without looping through what would probably be dozens of queries.
To try and be a bit clearer, what i'd like is a query which would work something like (deliberate pseudo code):
SELECT * FROM table where location = 'location' AND if($availability !='Any') { available = '$available' } etc etc
Is something like this possible?
Or can I create a single string of all $_POST fields that !='Any' and then carry out a search on a row that contains all the words in the string (which I think would work in theory)?
I hope this makes sense to someone and you can point me in the right direction.
P.S. All $_POST is escaped and secured before interacting with database, just not included here :)
Try this:
$sql = "SELECT * FROM table where 1 ";
foreach ($_POST as $key => $post) {
if ($post != 'Any') {
$sql .= " AND $key = '$post' ";
}
}
// now you can run $sql against the database
Could you for argument sake collect all of the $_POST into a foreach($key=>$val) and then run the key through a switch or if statments that appends "AND x=x " to the statement?
Something like:
$sql = "SELECT * FROM table WHERE required='required'";
foreach($_POST as $key=>$val){
if(!empty($val)){ $sql .= " AND ".$key."='".$val"'"; }
}
Not sure if that works but in theory that is what i thought of first.
Thanks to those who offered answers, however I used the suggested answer found in the link above my question as it was clearer to me. Sample code pasted below FYI:
$tmp = "where ";
if($A and $A!="any" and $A!="not used")
$tmp .= "row1 = '".$A."'";
if($B and $B!="any" and $B!="not used")
$tmp .= "AND row2 = '".$B. "'";
if($C and $C!="any" and $C!="not used")
$tmp .= "AND row3 = '".$C."'";
$db_q = "Select * from table $tmp";
Thanks again, don't know where I'd be without SO.
I have some search functionality that works with 3 drop down boxes. Based on the criteria chosen, a profile is returned. The 3 drop downs are:
County
Constituency
Gender
Now I am trying to build a query but have just realised that actually a person does not have to choose an option from each drop down and nor do I want them to.
So for instance I do not want to disable the search button until an option is selected from each drop down.
Having chosen a value from any drop down, and possibly having no value selected from any drop down at all, and just clicking the search button, I am trying to understand how I can cope with the unknown combinations.
My first thought was that I could use something like a truth table but I imagine this is simply overkill and in fact this is a very common piece of functionality.
Then I thought maybe I could have something like:
$county = "$_GET['county'];";
$constituency = "$_GET['constituency'];";
$gender = "$_GET['gender'];";
Then I could check to see if they are empty and somehow use this value, e.g.
if($county !== '') {
???SOMEHOW MAKE USE OF THIS IN AN SQL QUERY???
PERHAPS PASS IT TO ANOTHER PARAMETER
$sqlparams = "county = '$county'";
}
SELECT * FROM profile
WHERE {$sqlparams};
I think I'm on the right tracks but could use some guidance.
All help is greatly appreciated.
This should do want you want, I think.
<?php
$tooLookFor = array("county", "constituency", "gender");
foreach($tooLookFor as $key){
if(isset($_GET[$key]) && strlen($_GET[$key])>0){
$queryParams[] = $key.'="'.$_GET[$key].'"';
}
}
$query = "SELECT * FROM profile WHERE ".implode(' AND ', $queryParams);
?>
You could do something like:
$county = $_GET['county'];
$constituency = $_GET['constituency'];
$gender = $_GET['gender'];
$sqlparams = array();
if($county !== '') {
$sqlparams[] = "county = '$county'";
}
if($constituency !== '') {
$sqlparams[] = "constituency = '$constituency'";
}
if($gender !== '') {
$sqlparams[] = "gender = '$gender'";
}
$query = "SELECT * FROM profile";
if (count($sqlparams) > 0) {
$query .= " WHERE " . implode(" AND ", $sqlparams);
}
You can do that with something like this:
$where = array();
//repeat as needed
$where[$column] = $value;
$where2 = array();
foreach($where as $key => $value){
$where2[] = "$key = '$value'";
}
$where_string = implode(' AND ', $where2);
$where_string will have the string to insert after WHERE.
Yes, you are on the right track, you're just not at the right switch yet. ;)
You can't build the query until you know what you have to work with. So first, in your validation, determine (as you are doing) with the key words actually are and what fields they represent. Presumably these map to fields in tables, maybe 3 tables? Point is, your query will need to be dynamically built.