I have a database table set up in the following way:
table
--------
id: 123
name: test
description: lorem ipsum
a: NULL
b: NULL
c: NULL
d: lorem ipsum
e: NULL
f: lorem ipsum
Then I have a variable on my PHP page, $id = 123
How can I return the name of the first NOT NULL column, searching in a, b, c, d, e, f
only? So in this instance, the query would return d
or f
into a string. (NOT lorem ipsum
)
Here's something I've tried for you to get a better understanding of what I need:
(as far as I know, COALESCE()
will "return the first non-NULL argument")
$cat = mysql_query("SELECT coalesce(a, b, c, d, e, f) FROM table WHERE `id`='$id' LIMIT 1");
$cat = mysql_fetch_assoc($cat);
$cat = array_shift(array_values($cat));
The query above almost does what I want, it returns the information of the first NOT NULL column (so in this instance, it returns lorem ipsum
)... What I need is the NAME of that column.
So then I tried $cat = mysql_field_name($cat, 0);
(see below for info) - but apparently this needs to be ran on the query, not the string returned from mysql_fetch_assoc
. So I tried doing exactly that and running mysql_field_name
on the query, and it returns part of the original query (coalesce(a, b, c, d, e, f)
) when I echo it. Weird huh?
(info —mysql_field_name
— Get the name of the specified field in a result)
For recap: The 3 lines of PHP I provided are working and provide information from a column, but I need a way to get the NAME of that column and store it into a string. Thanks
After following Gordon's method I changed the first line of my PHP in the example above (the query) to $cat = mysql_query("select (case when a is not null then 'a' when b is not null then 'b' when c is not null then 'c' when d is not null then 'd' when e is not null then 'e' when f is not null then 'f' end) FROM directory WHERE id='$id' LIMIT 1")
but it returns a boolean (so I can't run mysql_fetch_assoc
as it isn't actually returning anything), I have checked all names of columns are correct etc.