douna4762 2016-10-04 15:34
浏览 10

PHP从具有列标题名称的mysql中选择

I have the following PHP 5.4 script which selects from MySQL 5.7, and it works fine.

<?php
$link = new mysqli("localhost","my_username","my_password", "my_schema");
  if (mysqli_connect_errno())
   {
   printf("Connect failed: %s
", mysqli_connect_error());
  exit();
}
$sugg_query = 
"SELECT 
    s.prim_key, 
    s.created_date,
    s.created_by,
    s.suggestion 
FROM suggestion s;";
if ($sugg_result = mysqli_query($link, $sugg_query))
{
// determine number of rows result set */
    $sugg_row_cnt = mysqli_num_rows($sugg_result);
    printf("Result set has %d rows.
", $sugg_row_cnt);

    while($sugg_row = mysqli_fetch_array($sugg_result))
    {
    echo "<br />";
    echo 
    $sugg_row['prim_key'] . " " . 
    $sugg_row['created_date'] . " " .
    $sugg_row['created_by'] . " " .
    $sugg_row['suggestion'] . " " ; 
    }
    /* close result set */
    mysqli_free_result($sugg_result);
}
//Close the connection
mysqli_close($link);
//close PHP
?> 

I'd like to add column headers to the result. If I change the SELECT statement to the following, I get a result where only the row count line is produced.

$sugg_query = 
"SELECT 
    s.prim_key as 'Key', 
    s.created_date as 'Date',
    s.created_by as 'Source',
    s.suggestion as 'Suggestion' 
FROM suggestion s;";

How can I obtain data values and column headers from a SELECT in PHP?

  • 写回答

1条回答 默认 最新

  • dongliang1873 2016-10-04 15:54
    关注

    For getting the headers you can iterate a row like:

    foreach($sugg_row as $header => $value){
        echo $header;
    }
    

    So maybe something like this should work in your code:

    $rows = mysqli_fetch_array($sugg_result)
    foreach($rows[0] as $header => $value){
        echo $header;
    }
    

    You need also to keep in count that mysqli_fetch_array() will return NULL if there is no rows

    评论

报告相同问题?

悬赏问题

  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离