Home > Enterprise >  How do I add a comma after every string(php)
How do I add a comma after every string(php)

Time:09-19

So the code below gets a name from a db(which is a string) and it outputs with "" and a comma.Well it was suppose to, but for some reason it only adds the quotation marks and not the commas.I need it to add the commas too.Thank for you help.

   <?php
$sl = "SELECT _eName FROM vrt;";
$ret = mysqli_query($conn, $sl);
$resultck = mysqli_num_fields($ret);
if ($resultck > 0){
 while ($row = mysqli_fetch_assoc(($ret))){

  $b = $row['e_Name'];
  $temp = array($b,);


  $req = "'" . implode ( "' , '", $temp ) . "'";
  
 echo $req;
  
   
  

 }}
?>

CodePudding user response:

You're echoing each row, your not building out $temp with all rows then imploding, so it would only contain the one item.

Instead, simply do:

<?php
$conn = ...
$result = mysqli_query($conn, "SELECT e_Name FROM vrt");

$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$data = array_map(fn($row) => $row['e_Name'], $data);

echo "'" . implode ("' , '", $data) . "'";
?>

CodePudding user response:

implode joins array elements with a string. Your variable $temp contains only a single element, so there is nothing to join and the element itself is returned.

  •  Tags:  
  • php
  • Related