I'm trying to create a SQL Query that gets data from my DB depending on what the array includes.
Example:
My array includes 1, 2, 3 then the query should be SELECT * FROM v WHERE category='1' OR category='2' OR category='3'.
Does anyone know a way to achieve this?
Any tips are welcome.
UPDATE:
Using MySQL as DB.
You can use implode function and IN clause as
$sql="SELECT * FROM v WHERE category IN ('".implode("','", $your_array)."')";
I would take a look at https://stackoverflow.com/a/14767572/755949, which uses placeholders and PDO to add the parameters to your query. Going with Saty's answer you could risk ending up with a SQL injection.
$where = 'WHERE category="' . implode('" OR category="', $array) . '"';
You can also try:
$sql = "SELECT * FROM v WHERE ( FIND_IN_SET(".implode("','", $your_array).", category) ) ";
For more info about FIND_IN_SET: http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php
Related
How do you bind an array for an IN clause in arbitrary SQL using the createCommand() statement?
$sql = ... "where campaign.id not in (:notThese) " ...
$campaignId = Yii::$app->db->createCommand($sql)
//->bindValue(':notThese', ...)
->queryScalar();
I'm using createCommand() because I'm using group by and having. This is similar to this question & answer https://stackoverflow.com/a/31753889/148844 but I was hoping for a more elegant way in Yii. That accepted answer is for updates. The other answer is awkward. createCommand() doesn't seem to have any functions for IN clauses.
some examples which i guess will help you:
$values=[4,1];
$campaignId = (new \yii\db\Query())->from('campaign')->where(['not in','campaign.id',$values])->groupBy(['groupcolumn'])->scalar();
// SELECT * FROM `campaign` WHERE `campaign.id` NOT IN (4, 1) GROUP BY `groupcolumn`;
$campaignId = (new \yii\db\Query())->from('campaign')->groupBy(['groupcolumn'])->having(['not in','campaign.id',$values])->scalar();
// SELECT * FROM `campaign` GROUP BY `groupcolumn` HAVING `campaign.id` NOT IN (4, 1) ;
You should use the yii\db\Query to use such features
$campaignId = (new \yii\db\Query())->from('campaign')->where(['in','campaign.id',$values])->scalar();
My database table has many columns.
I want to do a search based on multiple columns.
Sometimes it may not be the value of some columns.
How do these fields in sql query to be ineffective?
Thank you.
for examle:
$C1=$_POST[c1];
$C2=$_POST[c2];
SELECT * FROM mytable WHERE column1='$c1' AND column2='$c2'
i want if C2 be nulled, disable it from sql query.
One way is:
if(!$_POST[C2]){
SELECT * FROM mytable WHERE column1='$c1'
}
...
I want do it through sql query to do because My table has many columns.
First, you should never write queries with variables inside like that. Learn about PDO / mysqli and prepared statements.
Second, key references for an array should either be a string or integer; the expression $_POST[c1] will most likely cause a notice and implicit conversion to a string. It's better to write $_POST['c1'].
Third, and to answer your question, you can use isset() and strlen() to determine whether a value is "empty", i.e. empty string.
$params = array($_POST['c1']); // you should also check whether $_POST['c1'] is defined too
$sql = 'SELECT * FROM `table_name` WHERE column1 = ?';
if (isset($_POST['c2']) && strlen($_POST['c2'])) {
$sql .= ' AND column2 = ?';
$params[] = $_POST['c2'];
}
$stmt = $db->prepare($sql);
$stmt->execute($params);
Build an array of conditions by iterating through the POST values, adding a condition if the respective POST parameter is not empty:
$conditions = array();
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$conditions[] =
$dbcolumn[$key] . " = '" . mysql_real_escape_string($value) . "'";
}
}
You will need an array $dbcolumn that matches POST variables to the database columns (or you have to provide some other means of translating between the two).
Now create a SQL query for the given conditions:
$query = 'SELECT * FROM mytable';
if (!empty($conditions)) {
$query .= ' WHERE ' . join(' AND ', $conditions);
}
Note that the extension that provides mysql_real_escape_string() is deprectaded. You should probably use some other extension to comunicate with the MySQL server and would than have to use the repsective call of the other extension.
This code not recomended, but if you realy want to do it on MySQL, you can use LIKE syntax like this:
SELECT * FROM mytable WHERE column1="$c1" AND column2="$c2%"
Add % character before or after $c2
Please don't do it!!
This question already has an answer here:
Bind multiple parameters into mysqli query
(1 answer)
Closed 5 years ago.
I need to make a simple query
$array_of_ids = array();
//poulate $array_of_ids, they don't come from another db but from Facebook
//so i can't use a subquery for the IN clause
$wpdb->prepare("SELECT id from table where id IN (%d, %d)", $array_of_ids [0], $array_of_ids [1]);
The question is, if i have 200 elements in the array, what is the correct way to handle this?Do i have to manually build the query with 200 %d? I need this query because i must "sync" my database with facebook data and i have to check if the user i have in the db are present, update those that are present, insert new users and delete those that are not my friend.
If you know for certain that the array elements are numeric:
$wpdb->prepare("SELECT id FROM table WHERE id IN ("
. implode(',',$array_of_ids) . ")");
Otherwise, you can use the vsprintf form of prepare to pass in the array of parameters:
$wpdb->prepare("SELECT id FROM table WHERE id IN ("
. str_repeat("%d,", count($array_of_ids)-1) . "%d)" , $array_of_ids);
I'm not sure that this is a good approach, but you could do it in this fashion:
$sql = "SELECT id from table where id IN ("
. implode(',', array_fill(0, count($array_of_ids), "%d"))
. ")";
call_user_func_array(array($wpdb, 'prepare'), $array_of_ids);
This builds a string with the appropriate number of %d, then uses call_user_func_array to do it dynamically.
That said, I'm not sure this is really a case where prepared statements are worth the hassle, given how easy it is to sanitise integers.
Yes, dynamic sql is the way here. Fortunately, integers are easy to not screw up with.
$vals = array_filter(array_map('intval', $vals));
make sure you have at least one value and then implode it. Not need for a prepared statement here, just execute the sql.
Since this has no accepted answer yet I'll go with my approach with array_filter
$array_of_ids = array(0,1,1,2,3,5,8,13);
echo "SELECT id from table where id IN (".implode(',', array_filter($array_of_ids,'is_int')).")";
will output
SELECT id from table where id IN (0,1,1,2,3,5,8,13)
while
$array_of_ids = array('zero',1,true,2,3,5,8,'thirteen');
echo "SELECT id from table where id IN (".implode(',', array_filter($array_of_ids,'is_int')).")";
will output
SELECT id from table where id IN (1,2,3,5,8)
Please note that is_int doesn't work with $_GET variables so use is_numeric instead
You can do this :
$query = $wpdb->prepare("SELECT id from table where id IN :param");
$query->bindParam("param", "(".implode(',', array_map('intval', $array_of_ids)).")");
I need to create a select query which fetches records according to multiple variables
like:
<?PHP
#$task=$_REQUEST['task'];
#$Country=$_REQUEST['Country'];
#$City =$_REQUEST['City'];
#$MosqName =$_REQUEST['txtMsqName'];
#$PostCode =$_REQUEST['txtPostalCode'];
$sql_serch="SELECT Country="."'".$Country."'", " City="."'".$City."'"." FROM job_mosqu";
?>
It is not working.
Don't forget to escape your input! NEVER put user-inputted variables (such as those from $_REQUEST) directly into SQL queries. Either use parametrized queries or escape the input using either mysql_real_escape_string, mysqli::real_escape_string or PDO::quote depending on what you're querying with...
Some reading on the subject:
PHP MySQL by example
StackOverflow question on it
Coding Horror
And to answer your actual question, use the WHERE clause.
SELECT * FROM job_mosqu WHERE Country = ? AND City = ? ...
There's plenty to read out there on using the where clause, just do some searching if you're not comfortable with it...
Tutorial on WHERE in mysql
Another Tutorial
And yet another
You are looking for AND
SELECT * FROM job_mosqu WHERE Country='$country' AND City= '$City'
Etc...
SELECT * FROM job_mosqu WHERE Country='$country' AND City= '$City' AND task = '$task' AND $MosqName = '$MosqName';
It is incorrect query. It is very bad query. May be you want next?
$task=$_REQUEST['task'];
$Country =$_REQUEST['Country'];
$City =$_REQUEST['City'];
$MosqName =$_REQUEST['txtMsqName'];
$PostCode =$_REQUEST['txtPostalCode'];
$sql_serch="SELECT `Country`, `City` FROM `job_mosqu` WHERE `City`='" . $City. "' AND `Country`='" . $Country . "'";
I've been trying to come up with something for a while now to no avail. My MySQL knowledge is rudimentary at best so I could use some guidance on what I should use for the following:
I have 2 tables ('bible' and 'books') that I need to search from. Right now I am just searching 'bible' with the following query:
SELECT *
FROM bible
WHERE text LIKE '%" . $query . "%'
ORDER BY likes DESC
LIMIT $start, 10
Now, I need to add another part that searches for some pretty advanced stuff. Here is what I want to do in pseudocode which I am aware doesn't work:
SELECT *
FROM bible
WHERE books.book+' '+bible.chapter+':'+bible.verse = '$query'
$query would equal something like Genesis 1:2, Genesis coming from books.book, 1 coming from bible.chapter and 2 coming from bible.verse
Any help/guidance on this is much appreciated =)
I would recommend designing a way in your application code to break up that query so that you search for the book, chapter, and verse separately from the keyword.
That means you need columns for book, chapter, and verse that are separate from the verse text.
You should also use a FULLTEXT index because the LIKE wildcard searches are extremely inefficient.
Here's how I'd run the query in PHP using PDO:
$quoted_query = $pdo->quote($query);
$sql = "SELECT * FROM bible
WHERE book = ? AND chapter = ? AND verse = ?
AND MATCH(text) AGAINST ({$quoted_query})"
$stmt = $pdo->prepare($sql);
$stmt->execute(array($book, $chapter, $verse));
I'd rather use a parameter for the fulltext query too, but MySQL doesn't support that.
You're close. To concatenate the fields use the CONCAT() function:
SELECT * FROM bible WHERE CONCAT(books.book, ' ', bible.chapter, ':', bible.verse) = '$query'
You can use MySQL concatenation:
SELECT *
FROM bible JOIN books
WHERE CONCAT(books.book, ' ', bible.chapter, ':', bible.verse) = '$query'
I'm not sure what your foreign key is linking books to bible, but that may need specification as well.
You need to parse the query into book, chapter and verse in php first.
A regular expression should work:
preg_match("/(.+)([0-9]+):([0-9]+)/",$query,$matches);
$book = trim(matches[1]); // use trim to remove extra spaces
$chapter = matches[2];
$verse = matches[3];
Then your sql query becomes:
SELECT *
FROM bible
WHERE books.book = '$book' AND bible.chapter= '$chapter' AND bible.verse ='$verse'
-- watch out for sql injection here! use prepared statements!