Greetings,
I'd like to figure out some syntax for retrieving the data from a table
when I don't know all the of field names. What I do know are, the name
of the table, the names of the primary key fields, and the names of the
fields I want to use in the "where" clause of the SELECT statement. All
of the examples I've seen in my books only show how to do this by
hard-coding the names of each of the fields, i.e.,
$userid=$query_data["userid"];
$userphone=$query_data["phonenum"];
etc.
What I've tried thus far, is to: first, retrieve the name of a field,
store that in a variable, and then, use that variable in the [""]
argument, but I can't get it to work. I also tried using an index,
unsuccessfully. I am able to get the field names successfully and
display them, so I know that part is working.
At the risk of testing patience but perhaps saving time, here's a code
snippet (trouble line is commented in caps, line 10).
Suggestions/examples appreciated.
//connect to the database
1. $linkid = db_connect();
//retrieve the field names of the specified table:
//the value of $userviewtable was passed from a previous line
2. $result=mysql_list_fields("mydatabasename",$uservi ewtable, $linkid);
//define a generic data query to get data from a selected record
3. $query = "select * from $userviewtable where userid='$userid' and
functional_area='$userviewarea';";
//execute the data query and store the result in a variable
4. $result2 = mysql_query($query);
//fetch the resulting data array from the variable
5. $query_data = mysql_fetch_array($result2);
6. mysql_close($linkid);
//at this point $result holds the field names,
//and $query_data holds the data from the selected record
//loop through the field names and use them as
//the arguments for getting the data values
7. echo "Data for selected record on table $userviewtable<br>";
8. for ($i=0; $i<mysql_num_fields($result); $i++) {
//this line seems to be working
9. $fieldname = mysql_field_name($result, $i);
//THIS IS THE TROUBLE LINE
10. $data_value = $query_data[$fieldname];
//note that I also tried these variations:
//["$fieldname"]; [".$fieldname."]; and [$i];
//result shows field names but no data
11. echo $fieldname: $data_value;
}
//end of snippet