如何从数据库中获取整个列并使用php将其存储在数组中?

时间:2022-07-19 22:13:19

My table's name is userdetails, it has four attributes named name, username, mobile and password. I want to get all the mobile numbers and store it in an array using php. I have used the following php code

我的表名是userdetails,它有四个名为name,username,mobile和password的属性。我想获取所有的手机号码并使用php将其存储在一个数组中。我使用了以下php代码

if($_SERVER['REQUEST_METHOD']=='GET'){
require_once('dbConnect.php');
$mobile  = $_GET['mobile'];
$sql = "SELECT MOBILE FROM USERDETAILS";

 $r = mysqli_query($con,$sql);

 $res = mysqli_fetch_array($r);

 $result = array();

 array_push($result,array(
 "MOBILE"=>$res['MOBILE']
 )
);

echo json_encode(array("result"=>$result));

mysqli_close($con);

  }

but all I am getting is the first entry of the database. Please help.

但我得到的只是数据库的第一个条目。请帮忙。

3 个解决方案

#1


1  

You should loop through the records by doing the following:

您应该通过执行以下操作来遍历记录:

$result = [];
while ($array = mysqli_fetch_array($r)) {
    $result[] = $array['MOBILE'];
}
echo json_encode($result);

#2


0  

For getting all number of column use while loop as

用于在循环时获取所有列数

 $jsonData = array();// initialized you array
    while ($array = mysqli_fetch_array($r,MYSQLI_ASSOC)) {// add MYSQLI_ASSOC to get associative array
        $jsonData[] = $res['MOBILE'];// store data into array
    }
    echo json_encode($jsonData);// convert in into json

#3


0  

Try this:

$result = mysqli_query($con,$sql);
$mob = Array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    $mob[] =  $row['MOBILE'];  
}

#1


1  

You should loop through the records by doing the following:

您应该通过执行以下操作来遍历记录:

$result = [];
while ($array = mysqli_fetch_array($r)) {
    $result[] = $array['MOBILE'];
}
echo json_encode($result);

#2


0  

For getting all number of column use while loop as

用于在循环时获取所有列数

 $jsonData = array();// initialized you array
    while ($array = mysqli_fetch_array($r,MYSQLI_ASSOC)) {// add MYSQLI_ASSOC to get associative array
        $jsonData[] = $res['MOBILE'];// store data into array
    }
    echo json_encode($jsonData);// convert in into json

#3


0  

Try this:

$result = mysqli_query($con,$sql);
$mob = Array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    $mob[] =  $row['MOBILE'];  
}