PHP Mysqli picks a value for multiple values ​​and shows the same for variances

I am trying to get multiple values ​​for multiple data I know how to retrieve for single data but I am new to get multiple data

let's say I want to select a mobile number for id 1,2,3 and show the mobile number for it with "," which I cannot reach

Expected

  • Select data from Master_table For id "1,2,3"
  • Show the Mobile_number of this particular ID as below.

Database

Master_table
name id  mobile_number
abcd 1   123456789
ssss 2   123456722
sssd 3   123456733
rrrr 4   123453389
iiii 5   123444789

      

PHP

$query="SELECT  mobile_number FROM Master_table  WHERE  id='1,2,3'" ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());

while($row=mysqli_fetch_array($data)){

    echo $row['mobile_number'];

}

      

Expected Result

123456789,123456722,123456733

      

+3


source to share


3 answers


You need to use the MySQL statement IN

:

Fixed SQL:

$query = "SELECT mobile_number FROM Master_table WHERE id IN(1,2,3)";

      

Explanation:

Select mobile_number

from table where id is 1, 2 or 3

The difference between =

and IN

is that when =

you can only compare one value.

With IN

you can compare with a set of values.



So the SQL stream:

SELECT mobile_number FROM Master_table WHERE (id = 1 OR id = 2 OR id = 3)

      

Which looks like:

SELECT mobile_number FROM Master_table WHERE id  IN(1,2,3)

      

As requested by the OP, the following updated code:

$query="SELECT  mobile_number FROM Master_table WHERE id IN( 1,2,3)" ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data)){
  $mobiles[] = $row['mobile_number'];
    //echo $row['mobile_number'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;

      

+4


source


Use the sentence IN

$query="SELECT  `mobile_number` FROM `Master_table` WHERE  `id` IN (1,2,3) " ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());

while($row=mysqli_fetch_array($data)){

    echo $row['mobile_number'];

}

      



See examples HERE

0


source


You can use a keyword IN

like this

$query="SELECT  mobile_number FROM Master_table  WHERE  id IN (1,2,3)" ;

      

0


source







All Articles