I have an mysqli table having values as such:-
id | price
65| 7000
67| 7001
And a php code to echo both out using an array variable:-
require('setup.php'); // got connection
$array = array(0 => 65, 1 => 67);
$d = implode("," , $array);
$sql = "SELECT price FROM trade WHERE id IN('$d')";
$query = mysqli_query($conn, $sql);
if($query){
while ($row = mysqli_fetch_array($query)) {
echo $row['price'].'<br>';
}
}
else {
echo mysqli_error($conn);
}
The output should come as
7000
7001
but it's only 7000
.
You need to do IN(65,67)
while you are doing IN('65,67')
So remove '
around $d
Code needs to be:-
$sql = "SELECT price FROM trade WHERE id IN($d)";
Note:- use fetch_assoc()
for lighter array iteration (as it only gives associative array resultset)
while ($row = mysqli_fetch_assoc($query)) {
Working snippet :- http://rextester.com/FEFBWZ40805
Try something like this:
require('setup.php');
$array = [65, 67];
$d = implode(',', $array);
$sql = "SELECT price FROM trade WHERE id IN($d)";
$query = mysqli_query($conn, $sql);
if($query){
while ($row = mysqli_fetch_assoc($query)) {
echo $row['price'].'<br>';
}
}
else {
echo mysqli_error($conn);
}
Remove extra single quotes in IN()
tag.
Corrected code:
$sql = "SELECT price FROM trade WHERE id IN($d)";
$sql
Outputs:
SELECT price FROM trade WHERE id IN(65,67)
You can check the code here:
Passing $d
withing quotes makes the IN('65,66')
look like this during execution so you need to remove that as by the default convention you just need to pass an array. So change your query to:
SELECT price FROM trade WHERE id IN($d)
Edit your query as below,
$sql = "SELECT price FROM trade WHERE id IN($d)";
Hope this helps.
Please check your SQL query
$sql = "SELECT price FROM trade WHERE id IN('$d')";
Please change this query like below:
$sql = "SELECT price FROM trade WHERE id IN($d)";
You should not use single quote with php varible.