mysqli_fetch_fields显示所有列名,即使该列中没有结果。
SHOW COLUMNS也做同样的事情。
我希望找到一种方法,只在列中有结果的情况下显示列名。
我能想到的唯一方法是为列名创建一个名为"column_name"的数组,然后迭代结果数组中的所有结果。如果有结果,请检查列名是否在column_name数组中,如果不在column_namearray中,则添加它。但这似乎占用了大量资源。有更快/更好的方法吗?
更新:这就是我想到的。。。。
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
$column_name=array();
$query="SELECT * FROM tablename";
$result=mysqli_query($link, $query);
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row);
foreach ($set as &$record)
{
foreach ($record as $key => $value)
{
if (isset($value))
{
if (in_array($key, $column_name))
{
//do nothing because the false flag doesn't work as expected.
}
else
{
$column_name[]=$key;
}
}
}
}
print_r($column_name);
作为一个例子,让我们考虑下表empty_columns
:
id col1 col2 col3 col4---------------------------------1 1 NULL NULL NULL2 NULL NULL NULL NULL3 1 1 NULL NULL4 NULL NULL NULL NULL5空1空6 1 NULL NULL 17 NULL NULL NULL NULL
如果我理解你的问题是正确的,那么你希望最终得到['col1', 'col2', 'col4']
,因为它们是唯一包含至少一个值的列。所以col3
不在其中,因为它只包含NULL值。
如果您要运行以下查询:
select
max(col1) as col1,
max(col2) as col2,
max(col3) as col3,
max(col4) as col4
from empty_columns
您将得到一个单行的结果,其中只有col3
包含NULL。然后,只需要在列上循环并检查NULL值,就可以得到结果。。。
如果我误解了什么,很抱歉。。。让我们大致假设一下。表(names
)结构:
id |name nbsp nbsp nbsp nbsp nbsp nbsp nbsp;|数据
1 |随机名称2|45820
2 | nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp;|45821
3 |随机名称3 |45822
4 | nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp;|45823
5 |随机名称5|45824
已编辑(更好的查询解决方案):
$sql = "SELECT * FROM names WHERE name != """;
$result = $db->query($sql);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
echo 'ID: '.$row['id'].' '.$row['name'].' '.$row['data'].'<br>';
}
else
echo '0 results';
旧版本:
$sql = "SELECT * FROM names";
$result = $db->query($sql);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
if (!empty($row['name'])) // All rows with empty values in 'name' column will be ignored.
echo 'ID: '.$row['id'].' '.$row['name'].' '.$row['data'].'<br>';
}
}
else
echo '0 results';*