PHP如何在while循环中从mysqli_fetch_field再次获取列名

时间:2015-09-16 04:05:59

标签: php mysqli

似乎mysqli_fetch_field仅在while循环中第一次返回列名。以下是我的代码

$LoginDetailsCon=mysqli_connect("100.100.100.100","root","root","db") or     die("Failed to connect to DB: " . mysqli_connect_error()); 
$LoginDetailsQuery="SELECT * FROM ewh WHERE UserName = 'SomeName' AND Date     BETWEEN '2015-09-01' AND '2015-09-30'";
$LoginDetailsResult=mysqli_query($LoginDetailsCon,$LoginDetailsQuery);
while ($row=mysqli_fetch_array($LoginDetailsResult,MYSQLI_ASSOC)) {
echo "1st time";
while($field=mysqli_fetch_field($LoginDetailsResult)) {
    $fieldname=$field->name;
    echo substr($fieldname,0,strlen($fieldname)-4) . "<br>";
}
echo "2nd time";
    while($field=mysqli_fetch_field($LoginDetailsResult)) {
    $fieldname=$field->name;
    echo substr($fieldname,0,strlen($fieldname)-4) . "<br>";
}
}
mysqli_close($LoginDetailsCon);

结果如下

1st timeUser
colname1withoutlast4characters
colname2withoutlast4characters
colname3withoutlast4characters
2nd time1st time2nd time1st time2nd time

我需要在while循环中获取列名,以仅从特定列获取结果并将其放入数组

1 个答案:

答案 0 :(得分:4)

你不需要mysqli_fetch_field。这个无用的功能,我不知道为什么有这么多的php用户试图使用它。

每次获取行时,您已将所有字段名称都作为生成的行数组键。

$con = mysqli_connect("100.100.100.100","root","root","db")); 
$sql = "SELECT * FROM ewh WHERE UserName = 'SomeName' AND Date BETWEEN '2015-09-01' AND '2015-09-30'";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($res)) {
    $fields = array_keys($row);
    foreach ($fields as $name) {
        // do whatever
    }
}