简体   繁体   English

MySQL / PHP:如何获取列和关联的数据

[英]MySQL/PHP: How to get columns and associated data

I know I can get the column/field names from a database by using: SHOW COLUMNS FROM tablename ...but is there a way I can get the columns returned as well as the content, so my return would be something like this: 我知道我可以使用以下方法从数据库中获取列/字段名称:SHOW COLUMNS FROM tablename ...但是有一种方法可以获取返回的列以及内容,所以我的返回将是这样的:

array[0][0] = column 1 name array [0] [0] =列1名称
array[0][1] = column 2 name array [0] [1] =列2名称
array[0][2] = column 3 name array [0] [2] =列3名称

array[1][0] = column 1 row 1 value array [1] [0] =第1列第1列的值
array[1][1] = column 2 row 1 value array [1] [1] =第2列第1行的值
array[1][2] = column 3 row 1 value array [1] [2] =第3列第1列的值

... ...

I'm looking to build a JSON object 我正在寻找建立一个JSON对象

jsonObj = { item 1 { jsonObj = {项目1 {
column 1 name: column 1 row 1 value, 第1列名称:第1列第1行的值,
column 2 name: column 2 row 1 value, 第2列名称:第2列第1行的值,
column 3 name : column 3 row 1 value... 第3列名称:第3列第1行的值...

Edit: I should add that I know the field names are returned with the query results 编辑:我应该补充一点,我知道字段名称与查询结果一起返回

(SELECT * FROM sometable) and if you use (SELECT * FROM sometable),如果您使用

while ($row = mysql_fetch_array($results)) { 
 $thisfield = $row['fieldname']; 
} 

But how can I access them (the field names) when I do not know them? 但是,当我不知道它们时,如何访问它们(字段名称)?

use mysql_fetch_assoc - it will return 使用mysql_fetch_assoc-它会返回

array( "name" => "value", "name2" => "value2" ... ); array(“ name” =>“ value”,“ name2” =>“ value2” ...);

then use json_encode( $data ) 然后使用json_encode($ data)

Using mysql_fetch_assoc() or the equivalent in whatever DB library you use will provide the column names as array keys. 在您使用的任何数据库库中使用mysql_fetch_assoc()或同等功能将提供列名作为数组键。

$results = array();
while ($row = mysql_fetch_assoc($db_result))
{
  $results[] = $row;
}
foreach ($results as $column=>$value)
{
  // loop over $column and $value
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM