【问题标题】:How to get the column names of a database table using implode in php如何在 php 中使用 implode 获取数据库表的列名
【发布时间】:2019-10-06 08:32:03
【问题描述】:

我想获取列列表而不是 implode 中的行,但它给了我一个错误,但是当我使用数组的索引号时给了我一行的结果。

<?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;

【问题讨论】:

  • 你能分享一些你目前得到的输出/错误吗?
  • $avengers = implode(",", array_column($id, 'name')); "Columns" 在这里有点模棱两可。调用 $rows $id 无济于事,其中 id 表示它是一个整数值。我会考虑使用更具描述性的变量名。
  • 非常感谢,您的建议解决了我的问题

标签: php sql mysqli phpmyadmin


【解决方案1】:
while ($show = mysqli_fetch_assoc($run_select)) {

      $id[] = $show;
     }

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

print_r($avengers);

这会以字符串形式返回表或数组中的列名/变量名的简单数组,这是我动态构建 MySQL 查询所需要的。

说明:-

<?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);
?>

输出:

Array
(
  [0] => Griffin
  [1] => Smith
  [2] => Doe
)

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多