Create MySQL query with IDs from results - php

I have a a form which let's the user select what they want to display. Now the results of this looks like that: 9, 10, 11. These are IDs from the table.
These are the IDs of the type they what to show. I have my query already, but I want to add this part at the end of my query.
So in this case:
$query = "type_ID = $result1 or type_ID = $result2 or type_ID = $result3"
if printed out with echo:
type_ID = 9 or type_ID = 10 or type_ID = 11
How can I achieve this?
I tried to loop and it,however this did not work and I am confused how to do add the MySQL code to this.
$result = $result . $_GET['type_ID'][$i]

I'm a tad unsure of what it is you are trying to achieve but from what I understand this should do it:
<?php
$tID = $_GET['type_ID'];
$query = 'SELECT * FROM table WHERE';
$i = 0;
foreach($tID AS $id){
if($i == 0){
$query .= ' type_ID = ' . $id;
$i++;
}else{
$query .= ' OR type_ID = ' . $id;
}
}
Although if you are only looking for the type_ID I'd still recommend using IN() like so:
<?php
$tID = $_GET['type_ID'];
$query = "SELECT * FROM table WHERE type_ID IN (" . implode(',',$tID) . ")";
In works just like OR, just instead of having to write multiple OR you can just use a single IN() :)

Have you try this ?
$sql = "SELECT * FROM table WHERE ".$query;

Related

Search and select multiple rows with different values then store into array?

Apologies if this has been asked before.
So here is my table:
|---ID---|---Colour--|
|---01---|----RED----|
|---02---|----BLUE---|
|---03---|----RED----|
I want to get ID 01 and 03 and store them into an array in one query:
SELECT ID FROM `users` WHERE `ID` IN ( 01, 03 )
and put it into an array that looks something like this:
$ID[0] = "01";
$ID[1] = "03";
Here is my PHP code for the query:
$test = "01";
$test2 = "03";
$checkID = "SELECT ID FROM users WHERE ID IN = ('" . $test . "', '" . $test2 . "')";
$result = mysqli_query($conn,$checkID);
How would I go about inserting the results into an array? Thanks to anyone who can help :)
you need to do a loop using mysqli_fetch_assoc()
while($row = mysqli_fetch_assoc($result)){
$ID[] = $row['ID'];
}
note:
(1) syntax is WHERE ID IN () without the =
(2) your query is $checkID so you need $result = mysqli_query($conn,$checkID); not $result = mysqli_query($conn,$checkUser);
also, not sure why are you selecting the ID using the ID.

passing array of values in sql select statement of where condition

$sql = "select id from table_name ";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row[id];
}
/* $data contains id's fetched from sql query from db.now i want to pass this id's(array of values) in $data array one by one to below select query in where condition and obtain desired result for each id.My question is how to pass an array of values to the below select statement I dont know how to do this.Any help is greatly appreciated.*/
$query = "select * from table where id1 = $data[] ";
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
You should use the cross database function in Moodle called get_in_or_equal()
list($where, $params) = $DB->get_in_or_equal($data, SQL_PARAMS_NAMED);
$sql = "SELECT *
FROM {table}
WHERE $id {$where}"
$records = $DB->get_records_sql($sql, $params);
You can use the IN clause.
When you are totally sure you only have numeric values in your $data array. You can do the following:
$query = "select * from table where id1 IN(" . implode(',', $data) . ")";
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";

echo all and entire MySQL Query rows in php without specifically naming each column

I have
$result = "";
if(someCondition)
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
else
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
$result could have 0 -> infinity rows returned
Table 1 and Table 2 have different amounts of columns with different names
I want to write 1 generic loop after the above else that will just print out all of the rows. Preferably 1 per line or deliminated.
To clarify, one of the two query calls will fill the $results variable with rows.
I wont know which one fills it at run time so I want to just do a print all contents to screen. Is there a method that does this? is there a fast loop that iterates through all of the rows without explicitly saying the column names?
bored enough to answer:
$result = "";
if(someCondition){
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
}else{
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
}
while ($row = mysql_fetch_array($result)) ) {
foreach($row as $key => $var)
{
echo $key . ' = ' . $var . '<br />';
}
}

How to correctly parse an array for an SQL query

When you need to do something like this:
SELECT * FROM userinfo WHERE id in (18,2,6,4,5)
And the id array comes from another query like:
$ids = $conn->fetchAll('SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
If I need to parse the array in order to give the right format to the query id do:
$norm_ids = '(';
foreach ($ids as $ids) {
$norm_ids .= $ids['origin'] .',';
}
$norm_ids = substr_replace($norm_ids ,"",-1) .')';
That outputs the ids like: (id1,id2,id3,id.......), so the I'll just: FROM userinfo WHERE id in ". $norm_ids;
But seems to ugly to me, is there a way to do this better?
You could do:
$idStr = rtrim(str_repeat('?,', count($ids), ',');
$query = 'SELECT * FROM userinfo WHERE id in (' . $idStr . ')';
and then use prepare():
$conn = $db->prepare($query);
$conn->execute($ids);
$res = $conn->fetchAll(...);
SELECT * FROM user_info WHERE id IN (SELECT origin from action ......) ....
Do you need the id's separate or can you combine them into 1 query?
perhaps something like:
SELECT * FROM userinfo WHERE id in (SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
this way you let the sql server do the work.
When i am faced with such situations, i use trim
$norm_ids_str = '';
foreach ($ids as $ids) {
$norm_ids_str .= $ids['origin'] .',';
}
$norm_ids = '(' . trim($norm_ids_str, ',') . ')';

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

Categories