0

I want to get the list of the columns and not the rows in the implode, but it's giving me an error, but gives me the result of a row when I use the index number of the array.

<?php
// this is the database connection
$session_id = session_start();
$con = mysqli_connect("localhost", "root", "", "ecommerce");
?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>array</title>
    </head>
    <body>
<?php
$sql_select = "SELECT * FROM cart";
$run_select = mysqli_query($con, $sql_select);
$datas = [];
if(mysqli_num_rows($run_select) > 0) {

    while($show = mysqli_fetch_assoc($run_select)) {

        $id[] = $show;
    }
}

$avengers = implode(",", $id['1']);
// i want to echo out the columns this is giving me the rows
echo $avengers;
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
  • can you share some output/error what you are getting currently? – har256b May 20 '19 at 00:29
  • `$avengers = implode(",", array_column($id, 'name'));` "Columns" is a bit ambiguous here. It doesn't help calling `$rows` `$id` where id implies that its a single integer value. I would consider using more descriptive variable names. – ArtisticPhoenix May 20 '19 at 00:44

1 Answers1

0
while ($show = mysqli_fetch_assoc($run_select)) {

      $id[] = $show;
     }

$avengers = array_column($id, 'COLUMN_NAME');

print_r($avengers);

That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries.

Explanation:-

<?php
// An array that represents a possible record set returned from a database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);

$last_names = array_column($a, 'last_name');
print_r($last_names);
?>

Output:

Array
(
  [0] => Griffin
  [1] => Smith
  [2] => Doe
)
Mohit Kumar
  • 952
  • 2
  • 7
  • 18