jvrothjr Posted March 5, 2007 Share Posted March 5, 2007 I have a query string that sets the value of Variables below: if ($DB == "Departments") { $tracking_id = $data22['tracking_id']; $dept_name = $data22['dept_name']; } simple and straight forward. Now I would like to set a loop that would set the variable name and value based on the field names in the table queried. if ($DB == "Departments") { $querystring = "Select * from ".$DB; $result=mysql_query($querystring); while(($field = mysql_fetch_field($result))) { $field->name = $data22[$field->name]; } } can I set the variable name using the $field->name if so how? I have tried this code with no luck and no luck searching. This is a small example. I have queries with fifteen plus fields. This would also remove the need to modify this code if a field needs to be added to the table. And yes I have had to add fields to the tables. Quote Link to comment https://forums.phpfreaks.com/topic/41280-solved-set-variable-name-use-field-name-from-table/ Share on other sites More sharing options...
sasa Posted July 1, 2007 Share Posted July 1, 2007 try if ($DB == "Departments") { $querystring = "Select * from ".$DB; $result=mysql_query($querystring); while(($field = mysql_fetch_field($result))) { $$field->name = $data22[$field->name]; } } Quote Link to comment https://forums.phpfreaks.com/topic/41280-solved-set-variable-name-use-field-name-from-table/#findComment-287439 Share on other sites More sharing options...
jvrothjr Posted July 2, 2007 Author Share Posted July 2, 2007 Nope no luck on that one Catchable fatal error: Object of class stdClass could not be converted to string in [$$field->name = $data22[$field->name];] Quote Link to comment https://forums.phpfreaks.com/topic/41280-solved-set-variable-name-use-field-name-from-table/#findComment-288295 Share on other sites More sharing options...
Petty_Crim Posted July 2, 2007 Share Posted July 2, 2007 This works for me: while($fld = mysql_fetch_field($result)) { $field_name=($fld->name); //assigns field name to a variable //makes a new variable with the name of the field ie a field called John makes a variable called $john ${"{$field_name}"} = $_POST[$fld->name]; } Quote Link to comment https://forums.phpfreaks.com/topic/41280-solved-set-variable-name-use-field-name-from-table/#findComment-288299 Share on other sites More sharing options...
jvrothjr Posted July 2, 2007 Author Share Posted July 2, 2007 thanks this worked $querystring = "Select * from ".$DB; $result=mysql_query($querystring); while(($field = mysql_fetch_field($result))) { ${"{$field->name}"} = $data22[$field->name]; } Quote Link to comment https://forums.phpfreaks.com/topic/41280-solved-set-variable-name-use-field-name-from-table/#findComment-288309 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.