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";
Related
My database looks like this:
I have a variable that looks like this:
$following = "John, Sarah";
I would like to get the rows where the column 'username' is in the variable $following (in this case, John and Sarah). To do this, I had a look at the answer https://stackoverflow.com/a/1356018/5798798 which suggested I use IN in my query, which I have attempted:
$following = "John, Sarah";
$stmt = $con->prepare("SELECT * FROM events WHERE username IN ('$following')");
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['eventtype'];
}
The problem is that the query is returning no data. My desired result would be:
spoke walked
From what I suggested in comments to use the following:
$following = "John, Sarah";
$following = explode(", ", $following);
$string = implode(", ", $following);
It ended up that I didn't include the quotes for the implode()'ing.
The final solution was to add the single quotes in the first parameter for the implode() function:
$following = implode("','",$following);
$following = join("', '", $following);
join no more returns an array. It is a string now.
You can use like this:
$in = str_repeat('?,', count($following ) - 1) . '?';
$stmt = $con->prepare("SELECT * FROM events WHERE username IN ($in)");
$stm->execute($following);
with out using join you directly implode array by the following way
$stmt = $con->prepare('SELECT * FROM events WHERE username IN ("'. implode('","', $following).'")');
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['eventtype'];
}
Note: $following always should be in array
I have SQL procedure in which I'm using an IN statment. It goes like this:
SELECT * FROM costumers WHERE id IN('1','2','12','14')
What I need to do is pass the values in to the IN statment as parameter which is an array in php, rather than hard-coded. How can I do that?
You can implode on this case:
$array = array('1','2','12','14');
$ids = "'".implode("','", $array) . "'";
$sql = "SELECT * FROM `costumers` WHERE `id` IN($ids)";
echo $sql;
// SELECT * FROM `costumers` WHERE `id` IN('1','2','12','14')
or if you do not want any quotes:
$ids = implode(",", $array);
You can use PHP function Implode
$array = array("1","2","12","14");
$query = "SELECT * FROM costumers WHERE id IN(".implode(', ',$array).")"
implode() is the right function, but you also must pay attention to the type of the data.
If the field is numeric, it is simple:
$values = array(1. 2, 5);
$queryPattern = 'SELECT * FROM costumers WHERE id IN(%s)';
$query = sprintf($queryPattern, implode(', ',$values));
But if it's a string, you must play with single and double quotes:
$values = array("foo","bar","baz");
$queryPattern = 'SELECT * FROM costumers WHERE id IN("%s")';
$query = sprintf($queryPattern, implode('", "',$values));
This should do the trick
$array = array('1','2','12','14');
SELECT * FROM `costumers` WHERE `id` IN('{$array}');
Try imploding the php into an array, and then interpolating that string into the SQL statement:
$arr = array('foo', 'bar', 'baz');
$string = implode(", ", $arr);
SELECT * FROM customers WHERE id in ($string);
use PHP's join function to join the values of an array.
$arr = array(1,2,12,14);
$sql = "SELECT * FROM costumers WHERE id IN(" . join($arr, ',') . ")";
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 ";
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'])."')"
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);