Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get SQL field names

Status
Not open for further replies.

3Y3

Programmer
Sep 18, 2001
45
CA
Hi,

I have a table in my database that contains several fields, which I am currently displaying the names of in my PHP, however I would like to ONLY get the names of the fields which have a value of 1 (as opposed to 0) in the row below.

ID Feature1 Feature2 Feature3
123 0 1 1
456 1 0 0

In the example case above, If I was checking the record based on an ID of 123 I wish for it to only return Features 2&3 (the name of the field)

Here is the code I have right now that grabs the field names (all of them only)

//Query the database
$query="select * from Features where ID = '$id'";
$nt=mssql_query($query);

// The total number of fields in the table
$i = mssql_num_fields($nt);

// Loop through the result set
for ($j = 1; $j < $i; $j++) {
echo "column $j\n ";
$fieldname = mssql_field_name($nt, $j);
echo "fieldname: $fieldname\n <br>";
}


This currently prints out the following data:
column 1 fieldname: Feature1
column 2 fieldname: Feature2
column 3 fieldname: Feature3
column 4 fieldname: Feature4
column 5 fieldname: Feature5



Any ideas how I can do this but based on the data in the below columns? Thanks for any help.
 
I think you're trying to go about this the wrong way. Instead of fetching only non-zero columns, fetch all the possible columns and only output the ones that are non-zero.

For that, all you need is to put your echo inside an if-statement



Want the best answers? Ask the best questions! TANSTAAFL!
 
Yup, figured that out just as you posted :)

Here is the code if anyone else searches these forums for it:


// Select all data from table based on ID
$query2="select * from HomeFeatures where ID = '$id'";

$nt2=mssql_query($query2);

// Total Number of Fields
$i = mssql_num_fields($nt2);

//
$row2=mssql_fetch_array($nt2);

// Loop through data
for ( $v=1; $v <$i; $v++ ) {

// If data is 1 (true) then print out the name
if ($row2[$v] == 1){
$column_name = mssql_field_name($nt2,$v);
print "Name: ".$column_name."</br>";
}
}


 
You know, you don't have to do separate fetches for values and columnname with mssql_fetch_array() and mssql_field_name().

I'd just use mssql_fetch_assoc(), which fetches values from the database in an associative array, with the columnnames as elements.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top