Mysql Query from an array [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
MySQL query using an array
How to use an array of values from PHP in the 'IN' clause of mysql query?
from a Post form i have an array like that
Array
(
[userid] => Array
(
[0] => 4e8329e97231c
[1] => 4e64b47849318
[2] => 4e4e415a30000
)
)
i am little struggle to retrieve the users data from mysql from this array
that should be something like this :
SELECT * FROM user_detail WHERE user_id='4e64b47849318' OR user_id='4e8329e97231c' OR user_id='4e4e415a30000'

Use implode().
$yourArray = array_map("mysql_real_escape_string", $yourArray);
$query = "SELECT * FROM user_detail WHERE user_id='";
$query .= implode($yourArray, "' OR user_id='");
$query .= "'";
Or indeed, use the SQL IN keyword:
$yourArray = array_map("mysql_real_escape_string", $yourArray);
$query = "SELECT * FROM user_detail WHERE user_id IN ('";
$query .= implode($yourArray, "','");
$query .= "')";

$clean_userid = array_map('mysql_real_escape_string', $arr['userid'])
$str_user_id = "'" . implode("', '", $clean_userid ) . "'";
$sql = "SELECT * FROM user_detail WHERE user_id IN ( $str_user_id )";

You can use the MySQL IN operator nicely here, it works like "OR" but you can essentially give it a list.
$user_id_string = implode(',', $array['userid']);
You now have a comma separated string of your user_id's.
Now query something like:
SELECT * FROM user_detail WHERE user_id IN ($user_id_string);

$criteria = "'".implode("','",$userID)."'";
$sql = "select * from user_detail where user_id in ($criteria)";

$query="SELECT * FROM user_detail
WHERE user_id='".(intval) $array['userid'][0]."'
OR user_id='".(intval) $array['userid'][1]."'
OR user_id='".(intval) $array['userid'][2]."'";

You could try
"SELECT * FROM user_detail
WHERE user_id IN ('". implode("','", $array['userid'])."')"

Related

Constructing mysql select from $_POST array

This is the $_POST array from my form.
Array ( [prescribedid] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 13 )
I want to create a select for any of items in the Array. I have written this, which produces the proper SELECT, but the if() to eliminate a trailing OR makes it clunky.
$query = "SELECT * ";
$query .= "FROM prescribed WHERE ";
for($i=0; $i<count($_POST["prescribedid"]); $i++) {
$query .= "prescribedid={$_POST['prescribedid'][$i]} ";
if($i < (count($_POST["prescribedid"])-1)) {
$query .= "OR ";
}
}
It produces this:
SELECT * FROM prescribed WHERE prescribedid=1 OR prescribedid=2 OR prescribedid=3 OR prescribedid=9 OR prescribedid=13
Is there another way to group the SELECTS or write the FOR() to make it cleaner, i.e. without the last IF().
$values=implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($values)";
Sanitization is on you :)
Hi You can Use In condition. use imploade function to find comma seoarated values
$data = array('prescribedid'=>array(1,2,3,9,14));
$query = 'SELECT * FROM prescribed WHERE prescribedid IN (';
$query .= implode(',',$data['prescribedid']).')';
echo $query ;
Output
SELECT * FROM prescribed WHERE prescribedid IN (1,2,3,9,14)
Use MySQL IN clause
$ids = implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($ids)";
You can simply use IN clause here.
Refer to MySQL IN clause
$query = "SELECT * FROM prescribed WHERE prescribedid IN ".implode(',', $_POST["prescribedid"]);

Select from database where username = any value within an array

I have an array called $friends and it has some values
$friends = array(); $friends[0] = 'Alex'; $friends[1] = 'Jake';
I want to be-able for my SQL query to select every array value in this case it is Alex and Jake
$q = "SELECT * FROM posts WHERE username='$friends' ORDER BY id DESC";
But I can't do that, I get a message saying "Notice: Array to string conversion in".
Please help I am quite new to PHP
Use implode make the array into a string with the values and use IN for lists in MySQL.
$friends = array('Alex','Jake');
$str = implode ("', '", $friends);
$q = "SELECT * FROM posts WHERE username IN ('". $str . "') ORDER BY id DESC";

mysql SELECT a whole column or cycle through all IDs

I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";

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

how to get values of array out

I have this array
$pv->orderRecordsArray = array();
foreach($order->records as $i=>$orderRecord){
$pv->orderRecordsArray[] = $orderRecord->orderRecordID;
}
// print_r($pv->orderRecordsArray) for example
// shows Array ( [0] => 46839 [1] => 46840 [2] => 46841 )
I need to use the array values from above in my sql statement below.
$sql = "
SELECT
*
FROM
table1
WHERE
orderRecordID IN (46741, 46742)
";
so infront of IN I want $pv->orderRecordsArray results.
thanks
You can use implode to generate such a list:
$sql = "SELECT *
FROM table1
WHERE orderRecordID IN (" . implode(', ', $pv->orderRecordsArray) . ")";
But you should also consider a subquery or Join of your tables.
$sql = 'SELECT *
FROM table1
WHERE orderRecordID IN ('.implode(',',$pv->orderRecordsArray).')';

Categories