croakingtoad Posted May 8, 2008 Share Posted May 8, 2008 Is there an easy way (other than manually setting the vars) to set var names as the database column name? I have a database that I am querying and then turning into an array like below-- # perform the query $SVresult = mssql_query($SVquery) or die("Cannot query database"); # fetch the data from the database $SVarray = mssql_fetch_array($SVresult) or die("Cannot process array"); $SVcount = count($SVarray); echo "Count: $SVcount <br /><br />"; # begin master loop through array for ($i = 0; $i <= $SVcount; $i++) { //print "$SVarray[$i]<br>"; print_r("$SVarray[$i] <br />"); } #end master loop through array Instead of having the vars returned having a value of say $SVarray[1] instead having a value of ColumnName or ColumnName[1]? Hope that makes sense. Thanks! Link to comment https://forums.phpfreaks.com/topic/104702-assigning-mysql-column-names-as-var-names/ Share on other sites More sharing options...
nickk Posted May 8, 2008 Share Posted May 8, 2008 instead of the last loop: foreach ($SVarray as $varName => $varVal) { $$varName = $varVal; } Link to comment https://forums.phpfreaks.com/topic/104702-assigning-mysql-column-names-as-var-names/#findComment-535856 Share on other sites More sharing options...
blackcell Posted May 8, 2008 Share Posted May 8, 2008 Is this what your talking about? <?php $log_priority = $row["log_priority"]; $log_date = $row["log_date"]; $log_name = $row["log_name"]; ?> Link to comment https://forums.phpfreaks.com/topic/104702-assigning-mysql-column-names-as-var-names/#findComment-535857 Share on other sites More sharing options...
BlueSkyIS Posted May 8, 2008 Share Posted May 8, 2008 this will load each column name as a variable with that column name and the value in that column. if you're getting more than one row, you'll need to put the mysql_fetch_assoc in a while loop. $qsql = "select * from ei_regions where id = '$id'"; $qresult = mysql_query($qsql) or die(mysql_error()); $data = mysql_fetch_assoc($qresult); foreach ($data AS $colname=>$value) { ${$colname} = $value; } Link to comment https://forums.phpfreaks.com/topic/104702-assigning-mysql-column-names-as-var-names/#findComment-535884 Share on other sites More sharing options...
croakingtoad Posted May 8, 2008 Author Share Posted May 8, 2008 I tried nickk's version but when I use the following-- foreach ($SVarray as $varName => $varVal) { $$varName = $varVal; echo "$DevName"; } it echoes out the value of the first rows column through every iteration instead of different values for $DevName. What do I need to change to have it assign the current columns value for that row in each iteration? Link to comment https://forums.phpfreaks.com/topic/104702-assigning-mysql-column-names-as-var-names/#findComment-535927 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.