gpt4 book ai didi

PHP 通过 'Key' => 'Value' 列回显所有表行 - 经验

转载 作者:行者123 更新时间:2023-11-29 08:08:01 24 4
gpt4 key购买 nike

尝试编写脚本来回显所有表格行的列信息,'Key' => 'Value' 对

我尝试执行以下步骤:*1.* 获取所有列字段2.运行 SELECT 查询3. echo JSON value Key as (表字段数)

$table_name = 'Users';
$fieldname=array();
$fieldnames=array();
$fieldnames_C; //fieldNames count


//--------------------------------------------- get colums 'key' array + count;
$result = mysql_query("SHOW COLUMNS FROM {$table_name}");
if (mysql_num_rows($result) > 0) {

while ($row = mysql_fetch_assoc($result)) {

$fieldname = $row['Field'];
array_push($fieldnames, $fieldname); //ARRAY ADD OBJECT
}

$fieldnames_C = count($fieldnames);
echo($fieldnames_C);
}


$users = array();
$query = mysql_query("SELECT * FROM {$table_name}");
//for table count
while ($row = mysql_fetch_array($query))
{
//for columns count
$i = 0;
while($i < $fieldnames_C)
{
$fieldname = $fieldnames[$i];


$users[] = array(

$fieldname => $row[$fieldname]

);

$i++;
}



array_push($users, $fieldname => $row[$fieldname]);

}


echo json_encode(array('response' => $users));
mysql_close($connection);
?>

输出如下:

[{"PID":"79"},{"UserID":"ofir"},{"UserName":"ofir name"},{"UserLat":"32.0511"},{"UserLon":"34.8029"}]

尝试这样的输出:简单的 JsonArray 作为表 SELECT 计数;

[{"PID":"79","UserID":"ofir","UserName":"ofir name","UserLat":"32.0511","UserLon":"34.8029"]

感谢您的回答!

最佳答案

您的代码可以大大简化:

$data = array();
$result = mysql_query("SELECT * FROM {$table_name}");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
$field_names = array_keys($data[0]);

当然,只有当您的查询实际返回任何结果时,这才能正常工作,但假设它确实返回,这实际上就是复制您正在做的事情所需的全部内容。

关于PHP 通过 'Key' => 'Value' 列回显所有表行 - 经验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22337086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com