Home > Net >  I need to fetch data from database but I need the result in this form of {data,data,}
I need to fetch data from database but I need the result in this form of {data,data,}

Time:05-31

<?php
  require_once 'includes/connection.php';
  $data = "select * from contacts_tbl";
  $query_posi = mysqli_query($con, $data);
  while($row = mysqli_fetch_array($query_posi)){
    echo $row['contact_number'];
  }
?>

the result of that is 09277432079 09236677868

What result I want is {09277432079,10236677868}

CodePudding user response:

I made a loop over your contacts array to demo the concept of visiting those data in a while loop and echoing contacts comma separated and wrapped in parenthesis:

https://onlinephp.io/c/6280d

$contacts = [
    '09277432079',
    '10236677868',
    '10436674963',
    ];

$arrayLength = count($contacts);
$i = 0;
echo '{';
while ($i < $arrayLength)
{
    echo $contacts[$i];
    if($i < $arrayLength-1)
        echo ',';
    $i  ;
}
echo '}';

CodePudding user response:

You need to create a variable with "{" as the initial value and then concatenate the iterations to your variable. Finally concatenate with "}".

<?php
  require_once 'includes/connection.php';
  $data = "select * from contacts_tbl";
  $query_posi = mysqli_query($con, $data);
  $result = "{";
  while($row = mysqli_fetch_array($query_posi)){
    $result.= $row['contact_number'].",";
  }
  //Delete the last comma
  $result = substr($result,0,1);
  $result.="}";
  echo $result;
?>
  •  Tags:  
  • php
  • Related