PHP: How to pass multiple values to SELECT query - php

I am new to PHP and hope someone can help me with this.
I currently use the below lines to retrieve a value from a db and to output it as an array with the item's ID and value which works as intended.
Now I would need to do the same for multiple items so my input ($tID) would be an array containing several IDs instead of just a single ID and I would need the query to do an OR search for each of these IDs.
I was thinking of using a foreach loop for this to append " OR " to each of the IDs but am not sure if this is the right way to go - I know the below is not working, just wanted to show my thoughts here.
Can someone help me with this and tell me how to best approach this ?
My current PHP:
$content = "";
$languageFrm = $_POST["languageFrm"];
$tID = $_POST["tID"];
$stmt = $conn->prepare("SELECT tID, " . $languageFrm . " FROM TranslationsMain WHERE tID = ? ORDER BY sortOrder, " . $languageFrm);
$stmt->bind_param("s", $tID);
$stmt->execute();
$result = $stmt->get_result();
while($arr = $result->fetch_assoc()){
$content[] = array("ID" => $arr["tID"], "translation" => $arr[$languageFrm]);
}
My thought:
foreach($tID as $ID){
$ID . " OR ";
}
Many thanks for any help,
Mike

There are two approaches, assuming $tID is an array of IDs
Using MySQL IN() clause
This will work also when $tID is not an array, but a single scalar value.
$tID = array_map('intval', (array)$tID); // prevent SQLInjection
if(!empty($tID)) {
$query .= ' WHERE tID IN(' . implode(',', $tId) . ')';
} else {
$query .= ' WHERE 0 = 1';
}
Using OR clause, as you suggested
A bit more complicated scenario.
$conds = array();
foreach($tID as $ID) {
$conds[] = 'tID = ' . intval($ID);
}
if(!empty($conds)) {
$query .= ' WHERE (' . implode(' OR ', $conds) . ')';
} else {
$query .= ' WHERE 0 = 1';
}

As per above conditions you can try with implode();
implode($tID,' OR ');
You can also use IN condition instead of OR something like this.
implode($tID,' , ');

Related

Output of DISTINCT and <> from SQL Query issue

I am obtaining some values from an array and making a match against these values in an SQL Query.
The code for this is as follows:
foreach($files as $ex){
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 4';
}
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
The issue that I am having is that the <> seems not to be working.. I have even tried using the != operator, but still having the same issue.
The output of $search from the array are :
101m
102l
102m
103l
The output of SQL from the query is still:
101m
102l
102m
103l
Your code doesn't seem that logical, as you generate numerous SQL statements and then just execute the last one.
However I assume what you want to do is take a list of files, extract a string from each file name and then list all the pdb_code values from the table which are not already in the string.
If so something like this would do it. It takes each file name, extracts the sub string and escapes it, putting the result into an array. Then it builds one query, imploding the array to use in a NOT IN clause:-
<?php
$search_array = array();
foreach($files as $ex)
{
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$search_array[] = mysql_real_escape_string($search);
}
if (count($search_array) > 0)
{
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('" . implode("','", $search_array) . "') LIMIT 4";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
}
You have to use not in:
SELECT * FROM table_name WHERE column_name NOT IN(value1, value2...)
Try this:
$searchIds = implode(',',$search);
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('$searchIds') LIMIT 4";

Mysql query for multiple array values

I have this query:
$relatedtags = $video->tags;
$relatedtagsagain = explode(",", $relatedtags);
$query_parts = array();
foreach ($relatedtagsagain as $item) {
$query_parts[] = "'%".mysql_real_escape_string($item)."%'";}
$string = implode(",", $query_parts);
$result = $cachedb->get_results("SELECT ".DB_PREFIX."videos.title,".DB_PREFIX."videos.id as vid,".DB_PREFIX."videos.thumb, ".DB_PREFIX."videos.views,".DB_PREFIX."videos.duration,".DB_PREFIX."users.name, ".DB_PREFIX."users.id as owner FROM ".DB_PREFIX."videos LEFT JOIN ".DB_PREFIX."users ON ".DB_PREFIX."videos.user_id = ".DB_PREFIX."users.id where ".DB_PREFIX."videos.tags LIKE {$query_parts[0]} OR ".DB_PREFIX."videos.tags LIKE {$query_parts[1]} limit 0,".get_option('related-nr')." ");
How can get results for more $query_parts[] like $query_parts[2] and $query_parts[3] or from all the array? using LIKE $query_parts[] wont work.
lets go back to the basic of programming, this can be solved in many ways, like using array_mapping(see comment of scrowler), loops and many more:
sample using foreach loop:
foreach ($relatedtagsagain as $item) {
$query_parts[] = " videos.tags LIKE " . "'%". mysql_real_escape_string($item) . "%' ";
}
$parsed_query_parts = implode('OR', $query_parts);
$result = $cachedb->get_results("SELECT ".DB_PREFIX."videos.title,".DB_PREFIX."videos.id as vid,".DB_PREFIX."videos.thumb, ".DB_PREFIX."videos.views,".DB_PREFIX."videos.duration,".DB_PREFIX."users.name, ".DB_PREFIX."users.id as owner FROM ".DB_PREFIX."videos LEFT JOIN ".DB_PREFIX."users ON ".DB_PREFIX."videos.user_id = ".DB_PREFIX."users.id WHERE" . $parsed_query_parts . " limit 0,".get_option('related-nr')." ");

PHP 'Where' query conditional on 'If' 'isset'

I am new to PHP so any help on the following would be really appreciated:
I am trying to run a query with a WHERE condition, but I only want to apply the where condition if the variable has been set (via a radio button).
I basically want to be able to say - if a variable is not set, do not include it in the where condition. The complication is that I will be doing this with 3+ variables...
At its most basic - here is the code I have so far:
if(isset($_POST['category'])){
$category = $_POST['category'];}
if(isset($_POST['brand'])) {
$brand = $_POST['brand'];
}
{
$q = 'SELECT name, category, brand, price, imageurl, purchaselink FROM clothes WHERE category = "'.$_POST['category'].'" AND brand = "'.$_POST['brand'].'"';
[truncated]
Thanks very much in advance!
You can do this with an array, but first of all DO NOT BUILD QUERIES THIS WAY since you'll be vulnerable to SQL injection. Use PDO instead.
The idea is to have a list of suitable conditions:
$conds = [ 'brand', 'category', 'name' ];
$where = [ ]; // Empty array
foreach ($conds as $cond) {
if (!empty($_POST[$cond])) {
$sql = "({$cond} = ?)"; // We use PDO and bound values.
$where[$sql] = $_POST[$cond];
// In *deprecated* MySQL we would use at least
// $sql = "({$cond} = '" . mysql_real_escape_string($_POST[$cond]) . "')";
// $where[$sql] = true;
}
}
// Now we have a list of pairs:
// brand = ? => 'MyBrand',
// name = ? => 'MyName',
if (!empty($where)) {
$sql_string .= ' WHERE (';
$sql_string .= implode( ' AND ', array_keys($where) );
$sql_string .= ')';
}
// $sql_string is now SELECT ... WHERE ( (brand=?) AND (name=?) ... )
// Using the MySQL version, we would have ... WHERE ( (brand='MyBrand') AND ... ) )
// With PDO we PREPARE the query using sql_string
// http://dev.mysql.com/doc/apis-php/en/apis-php-pdo-mysql.html
// http://www.php.net/manual/en/intro.pdo.php
// We need an open PDO connection saved into $pdo
$stmt = $pdo->prepare ($sql_string);
// Then we execute the query.
// Bind the values to array_values($where).
$stmt->execute( array_values($where) );
while ($tuple = $stmt->fetch(PDO::FETCH_ASSOC)) {
...
}
A shorter way, MySQL only (since it does not distinguish between keys and values) would be
$where = [ ]; // empty array()
foreach ($conds as $cond) {
if (empty($_POST[$cond])) {
continue;
}
// THIS IS NOT SECURE. See e.g. http://johnroach.info/2011/02/17/why-mysql_real_escape_string-isnt-enough-to-stop-sql-injection-attacks/
$escaped = mysql_real_escape_string($_POST[$cond]);
$where[] = "({$cond} = '{$escaped}')";
}
$query = "SELECT ...";
if (!empty($where)) {
$query .= " WHERE (" . implode(' AND ', $where) . ")";
}
This approach has the additional advantage that you can have the 'AND' parameterized - the user can choose whether have the conditions ANDed or ORed via a radiobutton:
$and_or = ('OR' == $_POST['andor']) ? ' OR ' : ' AND ';
$query .= " WHERE (" . implode($and_or, $where) . ")";
Note that the actual value of 'andor' is NOT used -- if it is an OR, all well and good, ' OR ' is used. Anything else that might be accidentally sent in a POST by a customer, such as "--; DROP TABLE Students;" , is considered to mean ' AND '.
you have to incluide all inside if(){}
if(isset($_POST['category']) && isset($_POST['brand'])){
$q = 'SELECT name, category, brand, price, imageurl, purchaselink FROM clothes WHERE category = "'.$_POST['category'].'" AND brand = "'.$_POST['brand'].'"';
}
I use this technique to make my filters :
$q = 'SELECT name, category, brand, price, imageurl, purchaselink FROM clothes WHERE 1=1 ';
if(isset($_POST['category'])) $q .= ' AND category ="'.$_POST['category'].'"';
if(isset($_POST['brand'])) $q .= ' AND brand = "'.$_POST['brand'].'"';
// here you can add other filters. :) be happy

how can I avoid to many OR statements in a mysql query?

I am writing a code, where I have to produce a query with many OR statements, and I think there is a more comfortable way to this than:
foreach ($plz as &$value) {
if (empty($i)) {
$query = "WHERE plz='$value'";
} else {
$query = "$query OR plz='$value'";
}
$i++;
}
$sql = mysql_query("SELECT * FROM table $query");
while ($data = mysql_fetch_array($sql)) {
//do something
}
If you have multiple values a column may take, just connect them using the IN operator:
Instead of writing
... WHERE col=1 OR col=2 OR col=3
just write
... WHERE col IN (1,2,3)
To collect all entries in PHP, use an array and implode() later on:
// collecting values
$vals = array();
$vals[] = 1;
$vals[] = 2;
// ...
// add them to your query
$query .= ' WHERE col IN ( ' . implode( ',', $vals ) . ')';
// execute the query ...
In case your values are not integer, but need to be enclosed in apostrophes within the query, insert them that way into the array in the first place:
$vals[] = "'my string value'";
You're looking for ;
SELECT * FROM table WHERE plz in ('value1', 'value2', 'value3')
Be aware of SQL injections...
If the column plz is INT type, and all $plz are also integers, then:
$query = 'WHERE plz IN( ' . implode(',', $plz) . ')';
would work. Otherwise, trying this might work(not tested):
$query = 'WHERE plz IN( \'' . implode("','", $plz) . '\')';

Optimize this SQL query

I've got a SQL query within a foreach loop. Sometimes there can be many, and I mean a lot of queries to do, depending on several criteria, up to 78 queries potentially.
Now, I know that premature optimisation is root cause of all evil, but I don't want to see 78 queries - it's just not healthy.
Here's the code:
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT id FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$dsn = $db->query("SELECT msg, datetime FROM tbl_motd WHERE deptid = '" . $value . "'");
$motd = $dsn->fetch_assoc();
if ($motd['msg'] != "") {
<?php echo $motd['msg']; ?>
}
}
Can I make it any better?
Use IN MySQL operator to search over a set of values for id:
$ids = '"' . implode('", "',$crumbs) . '"';
$query1 = "SELECT id FROM tbl_depts WHERE id IN (" . $ids . ")";
$query2 = "SELECT msg, datetime FROM tbl_motd WHERE deptid IN (" . $ids . ")";
And so you will not need to retrieve all data you need using foreach loop, so you will have only 2 queries instead of 78.
Example: I have a table named table with 10 records which ids are: 1,2,3,4,5,6,7,8,9,10 (auto-incremented). I know I need records with ids 1,5,8. My query will be:
$sql = "SELECT * FROM `table` WHERE id in (1,5,8);";
And I don't understand why do you need to use & operator in foreach loop if you don't modify the $crubms arrays values.
I think this is want you want.
SELECT msg, datetime
FROM tbl_depts td
INNER JOIN tbl_motd tm ON td.id = tm.deptid

Categories