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

时间:2016-10-04 15:34:09

标签: php mysql

我有以下PHP 5.4脚本从MySQL 5.7中选择,它工作正常。

<?php
$link = new mysqli("localhost","my_username","my_password", "my_schema");
  if (mysqli_connect_errno())
   {
   printf("Connect failed: %s\n", 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.\n", $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
?> 

我想在结果中添加列标题。如果我将SELECT语句更改为以下内容,则会得到一个只生成行计数行的结果。

$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;";

如何从PHP中的SELECT获取数据值和列标题?

1 个答案:

答案 0 :(得分:1)

要获取标题,您可以迭代一行,如:

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

所以这样的事情可能会在你的代码中起作用:

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

如果没有行,你还需要记住mysqli_fetch_array()将返回NULL