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!

Link to comment
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.