List column name when value in a row equals......

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
malakajoe
Forum Newbie
Posts: 1
Joined: Sat Sep 18, 2004 2:38 pm

List column name when value in a row equals......

Post by malakajoe »

Hi,

I am trying to figure out how I can do this.

I want to return a column name when a value in a row = XXX. Here is an example.

I have an ID, so I can pull all data from the row in a select statement. I want to then find out the column name when any of 5 columns equals 1. Basically, these 5 columns can have 1 through 5 with no repeated values. Example results from query:

select * from testtable where id = '1';

Would return this

id = 1, testcolumn1 = 3, testcolumn2 = 2, testcolumn3 = 1, testcolumn4 = 5, and testcolumn5 = 4

I want to pull test3 column name.

Any help would be greatly appreciated.

THANKS!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

<?php


$result = mysql_query($sql) or die (mysql_error());

while ($row = mysql_fetch_array($result))
{
echo $row['testcolumn3'];
}

?>
I have no idea wut you meant, hopefully this is what you wanted
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

here's a ~basic way to do what you want, I think:

Code: Select all

<?php

$lookfor = 'testcolumn';
$valuelookfor = 1;
while($row = mysql_fetch_assoc($query))
{
  reset($row);
  while(list($k,$v) = each($row))
    if($v == $valuelookfor && preg_match('#^' . preg_quote($lookfor, '#') . '#', $k))
      echo $k . "<br />\n";
}
Post Reply