PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] How to get the column names of a database table using implode in php

 February 20, 2022     mysqli, php, phpmyadmin, sql     No comments   

Issue

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;

Solution

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
)


Answered By - Mohit Kumar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing