简体   繁体   中英

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.

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. I somehow need to include both INFORMATION_SCHEMA.COLUMNS as well as select * WHERE user = $user kinda stuff.

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. 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. You should use mysqli_* or PDO instead. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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