How to SELECT Comma Separated variable From Mysql - php

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}) ';

Related

How to concatenate equal sign and a variable such that result is usable in a mysql query of the type shown below?

I am running a mysql query based on several variables being posted from a bootstrap 4 form. I am struck at how to concatenate one of the posted variable 'prof' so as to use it for the query in two different scenarios: (1) When the user makes no choice and a NULL value is posted (2) When the user selects a particular profession and a specific value is posted. I need to concatenate the variable in a manner that I get the result of the type: = 'P01' and not just = P01 as it won't work in the mysql query: I am posting part of the code to show how I am handling the posted variable and the query itself. The query also includes some of the variables that i have been able to use successfully.
if(isset($_POST['prof_match']) && ($_POST['prof_match']) != 'NULL') {
$choice_prof = "= " . ($_POST['prof_match']); // Example P01 is Accountant
}else {
$choice_prof = 'IN(SELECT prof FROM profiles)';
}
// The query is as follows:
SELECT *
FROM profiles
WHERE age $choice_age
AND height $choice_ht
AND edn $choice_edn
AND prof $choice_prof;
The resulting string I get from the $choice_prof is quote = A01 unquote while what i need is quote = 'P01' unquote.
English not being my first language please ignore the syntax and grammatical mistakes. Thanks in anticipation.
As a means to kill 2 birds (solving your problem and sanitising your inputs) with one stone (using a prepared statement). You can do:
$parameters = [ $age, $height, $edn ]; //Actual values here, not values with condition
$sql = 'SELECT * FROM profiles WHERE age = ? AND height = ? AND edn = ? AND prof';
if(isset($_POST['prof_match']) && ($_POST['prof_match']) != 'NULL') {
$parameters[] = $_POST['prof_match'];
$sql .= '= ?';
}else {
$sql .= ' IN(SELECT prof FROM profiles)';
}
You can then execute this as a prepared statement.
PDO example:
$statement = $pdoObject->prepare($sql);
$result = $statement->execute($parameters);
It is similar in MySQLi as well.
Its very straight forward to use php variable and generate an sql string.
If you need quotation marks around your variable yo put them in your sql string like so:
$sql = "select * from table where some_column = '$variable'";
In your case, just put them in your string like this:
if ( !empty($_POST['prof_match']) ) {
$choice_prof = " = ' " . $_POST['prof_match'] . "'";
} else {
$choice_prof = 'IN(SELECT prof FROM profiles)';
}
SELECT *
FROM profiles
WHERE
age $choice_age AND
height $choice_ht AND
edn $choice_edn AND
prof $choice_prof;
For the empty() function refer to docs

How to write a query to check if a column value is in a PHP array that may be empty

I want to return records where a id field is in a php array. Usually I would do something like this:
$ids = array(1,2,3,4)
$query = "SELECT * FROM table WHERE statusId IN (" . implode(',',$ids) . ")";
However, if the $ids array happens to be empty, I get a error from mysql because of the empty parentheses. I can accomplish my goal using a subquery like this:
$query = "SELECT * FROM table WHERE statusId IN (SELECT statusId FROM statuses WHERE /* some conditions */)";
If the subquery is empty, then it will just return an empty record set without an error. I don't want to use the subquery because I already have the ids in the php variable.
Is there a way to write the first query so it doesn't return an error if the php array is empty? I know I can just write a conditional statement and just not run the query if the php array is empty. But for style reasons, I just want to see if there is a way to write the query that returns a empty set if the php array is empty.
You would better check if the array is empty. Just write:
if ( empty($ids) ) {
//Don't run query
}
$ids = array(1,2,3,4)
$idClause = !empty($ids) ? implode(',',$ids) : 'NULL';
$query = "SELECT * FROM table WHERE statusId IN (" . $idClause . ")";
try doing a ternary
$ids = array(1,2,3,4)
$query = !empty($ids) ? "SELECT * FROM table WHERE statusId IN (" . implode(',',$ids) . ")" : "SELECT * FROM table WHERE statusId IN (SELECT statusId FROM statuses WHERE /* some conditions */)";
;

give all rows if IN clause is empty in Mysql

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)

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.=");";

MySQL - How to select rows where value is in array?

Ok, normally I know you would do something like this if you knew the array values (1,2,3 in this case):
SELECT * WHERE id IN (1,2,3)
But I don't know the array value, I just know the value I want to find is 'stored' in the array:
SELECT * WHERE 3 IN (ids) // Where 'ids' is an array of values 1,2,3
Which doesn't work. Is there another way to do this?
Use the FIND_IN_SET function:
SELECT t.*
FROM YOUR_TABLE t
WHERE FIND_IN_SET(3, t.ids) > 0
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
If the array element is not integer you can use something like below :
$skus = array('LDRES10','LDRES12','LDRES11'); //sample data
if(!empty($skus)){
$sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "
}
If you use the FIND_IN_SET function:
FIND_IN_SET(a, columnname) yields all the records that have "a" in them, alone or with others
AND
FIND_IN_SET(columnname, a) yields only the records that have "a" in them alone, NOT the ones with the others
So if record1 is (a,b,c) and record2 is (a)
FIND_IN_SET(columnname, a) yields only record2 whereas FIND_IN_SET(a, columnname) yields both records.

Categories