give all rows if IN clause is empty in Mysql - php

I am trying to filter users using country wise . $country is an array containing the name of countries. I want to run the query in such a way that if there is nothing in country then the query gives me all the rows. how can i acheive this.
I am doing this :
"SELECT * from users where country IN('".implode("','",$country)."')";
thanks in advance

$sql = "SELECT * FROM users";
if($country) {
$sql .= " WHERE country IN('" . implode("','", $country) . "')";
}

For each filter item just check if it is NULL (i.e. don't filter the results based on this) or if it is equal/in:
SELECT *
FROM users
WHERE ('".implode("','",$country)."' IS NULL OR country IN('".implode("','",$country)."'))
AND ($forename IS NULL OR forename = $forename)

Related

Search Each Word Of a Search Using PHP MYSQL Search Query

I want to fetching Records On the Basis Of Entered Keywords in the Search Bar.
Suppose I have Below 3 Records in My SQL Table's Column
Beautiful Small Kid.
Beautiful Rabbit in the Zoo.
Natural Water.
Now, If the Search Query contains Beautiful, It will Return First 2 Records.
If the Search Query contains Beautiful (anything), It will Return Nothing.
I want those First 2 Records to be Displayed in this case too, Because It has the same word beautiful like in above searched Query.
Right Now, I am Using
SELECT * FROM table WHERE name LIKE '%value%' ORDER BY id ASC
Is there any Other Query or Method to Achieve Such Sort Of Results ?
SELECT * FROM table WHERE (name LIKE '%value1%') OR (name LIKE '%value2%') ORDER BY id ASC
etc
So, you would have to split up your search string into separate words.
$str = yourinput;
$strarray = (explode(" ",$str));
$query = "SELECT * FROM table WHERE ";
Foreach($strarray as $key=>$value){
If($key > 0){
$query = $query . "OR";
}
$query = $query . " (name LIKE '%" . $value . "%') ";
}
$query = $query . "ORDER BY id ASC";

How to SELECT Comma Separated variable From Mysql

I Have a MySql Database Structure and values samples as shown below:
sno firstname status
1 John Active
2 Kelly Inactive
3 Harri Passive
4 Kris Dormant
Now that I need to execute a Sql query from a PHP page, and the Status Values are from multiple checkbox which I have assigned as an array.
I have used Implode function for this array:
$status = $_POST['status'];
$mstat= implode (',', $status);
$query="SELECT * FROM USER WHERE status IN '$mstat'";
$result=mysql_query($query);
while ($members = mysql_fetch_assoc($result))
{
$fname= $members['firstname'];
echo $fname;
echo '</br>';
}
The problem is that I'm not getting any results. What could be the problem. Or If anyone could suggest/Advice for an alternative.
When I echo $mstat; I get Active,Passive,Dormant (That is based on my checkbox selection)
status are strings. You need to wrap them with quotes. And IN needs () to wrap the string values. Try -
$mstat= "'" . implode ("','", $status) . "'";
$query="SELECT * FROM USER WHERE status IN ($mstat)";
Assuming $status contains some or all of those values showed in database in array format.
Here is 100% working answer
$mstat= implode ("','", $status);
$query="SELECT * FROM USER WHERE status IN ('$mstat')";
IN works like this IN ('Active','Passive','Dormat')
so we have to add '' in all values which is done in implode function.
Change this line to:
$query="SELECT * FROM USER WHERE status IN ('$mstat')";
The Argument must in ()
!!!
EACH word must in ' '
like:
$query="SELECT * FROM USER WHERE status IN ('Active','Inactive')"
You can change it like:
if ($mstat) $query .= ' ({$db->quote($status}) ';

Select from table where value does not exist

I have a table (country_table) with a list of all countries and their respective ids.
|country_id|country_name|
|ES |Spain |
.
.
.
I have an array, fetched from another table using fetch_array that looks like this:
$array = Array(
[0]=>Array([country_id]=>'ES')
[1]=>Array([country_id]=>'DE')
[2]=>Array([country_id]=>'GB'))
How can I select the records (country_id and country_name) from country_table that do not exist in the table but exist in the array?
$sql ="SELECT country_id, country_name FROM country_table
WHERE country_id NOT IN (". implode(",", $array) .")";
implode() function will generate comma-seprated string representation of array elements .
This is the sql.
select country_id, country_name from table where country_id not in ('ES','DE','GB');
// gather unwanted id's first
$notInIds = array();
foreach ($array as $arr) $notInIds[] = $arr['country_id'];
// prepare query
$query = 'SELECT `country_id`, `country_name` FROM `your_table`
WHERE `country_id` NOT IN (' . implode(',',$notInIds) . ')';
// then execute it
For the question: "How can I select the records (country_id and country_name) from country_table that do not exist in the table but exist in the array?"
I guess you have to write some code (eg. in PHP) in order to achieve the result you want.
The problem is that you can not display data that is not in the table (eg. country_name), that's not possible as you don't know this data. The only possibility would to show the country_id's which are in the array and not in the table as this is the only data you have...

mysql query to assign value to the same variable from different columns

I have a table which has many columns but there are two main columns called District and State. My sql query is as follows.
$query = "SELECT * FROM table WHERE District = '" . $var . "' ORDER BY Date DESC";
this query returns me data from the district column.
Now this is what I want.In some rows the District column is empty, so in that case I want the query to lift data from State column. Is that possible?
Can that be done in mysql query or will I have to write something in php?
what do you mean by empty? If it is NULL then you should use COALESCE
SELECT *, COALESCE(District, State) NewDistrict
FROM...
but if it is empty as ''. then
SELECT *, IF(District = '', State, District) NewDistrict
FROM...
SELECT *
FROM table
WHERE District = '$var'
OR (District='' AND State='var')
ORDER BY Date DESC
$query = "SELECT * FROM table WHERE District = '" . $var . "' OR State = '" . $var . "' ORDER BY Date DESC";

Trying to get data from mysql table via php with IN clause (favorites)

Here is how my table "User" looks:
Name Password Favorites
Test Test 1 2 3 4
And in my table "Data" I have
Comment ID
"Test" 2
I want the the user to be able to save a comment to its favorites, hence the first table, where I save all favorites in one row, so the table doesn't get too big.
I try to get them all back by implode and IN clause.
Right now it does not seem to work and I hope that maybe someone here could give me some useful input on how to conquer this problem :)
$favoritenstring = ($GET_["favoritenstring"]);
$query = "SELECT * FROM $table_id WHERE ID in ('" . implode("','",$favoritenstring) . "')";
Right now I am getting this error on the above query line:
Invalid arguments passed
Your have to remove slashes from the string first:
$string = stripslashes($favoritenstring);
$query = "SELECT * FROM $table_id WHERE ID in " .$string;
Change This...
From
($GET_["favoritenstring"]);
TO
($_GET["favoritenstring"]);
Try this:
$query = "SELECT * FROM $table_id WHERE ID in ( ";
$myVars=explode($favoritenstring);
$numFavs=count(explode(' ', $favoritenstring));
for($i=0;$i<$numFavs;$i++)
{
$query.=$myVars[$i];
if($i<($numFavs-1))
{
$query.=", ";
}
}
$query.=");";

Categories