[英]PHP MySQL getting both the result as well as the column name of the table
I have always been getting the results of a database but never the column name, now I have a situation where i need both the column name and result together. 我一直都在获取数据库的结果,但是从来没有得到列名,现在我遇到了同时需要列名和结果的情况。
I have a simple code that shows the column name and adjacent to it show results where the results are = 1. 我有一个简单的代码,显示列名,并在其旁边显示结果,结果为= 1。
So let's say my table is looking like this 假设我的桌子看起来像这样
| Science | Maths | Biology | English |
---------------------------------------------------------
| 1 | 0 | 0 | 1 |
So basically what I am looking for is something like 所以基本上我想要的是
Table Name | Results
---------------------------------
Science | 1
English | 1
I search around the web and found the usage of INFORMATION_SCHEMA.COLUMNS but that doesn't seem to work in the way I wanted it to. 我在网上搜索并发现了INFORMATION_SCHEMA.COLUMNS的用法,但这似乎不符合我想要的方式。 I somehow need to include both INFORMATION_SCHEMA.COLUMNS as well as select * WHERE user = $user kinda stuff.
我以某种方式需要同时包含INFORMATION_SCHEMA.COLUMNS和select * WHERE user = $ user kinda之类的东西。
My approach. 我的方法。
$i = 0;
$result = mysql_query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'trophy' WHERE UPPER(username) = UPPER('$searchuser')");
while($row = mysql_fetch_array($result))
{
echo $row['COLUMN_NAME'];
echo '-'
echo $row[$i];
$i++;
}
The best way to approach this would probably be by fetching an associative array and using its keys. 解决此问题的最佳方法可能是通过获取关联数组并使用其键。 From your example it seems you always expect to get 1 result row, but to prevent problems I will add a
LIMIT 1
anyway. 从您的示例看来,您总是希望得到1个结果行,但是为了防止出现问题,我还是会添加
LIMIT 1
。 You could do something like this: 您可以执行以下操作:
$result = mysql_query("SELECT * FROM trophy WHERE username = '$searchuser' LIMIT 1");
$result = mysql_fetch_assoc($result);
foreach ($result as $name => $value)
echo $name . '-' . $value;
Note that the mysql_*
functions are deprecated though. 请注意,虽然不建议使用
mysql_*
函数。 You should use mysqli_*
or PDO
instead. 您应该改用
mysqli_*
或PDO
。 You can compare them here . 您可以在这里进行比较。
while ($row = mysql_fetch_array($result, **MYSQL_BOTH**)) {
printf ("ID: %s Name: %s", $row[0], $row["name"]);
}
http://php.net/manual/en/function.mysql-fetch-array.php http://php.net/manual/en/function.mysql-fetch-array.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.