Jump to content

assigning mysql column names as var names?


croakingtoad

Recommended Posts

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!

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;
}

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.