Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I seem to have looked everywhere for this.

Here is the code i use to set a variable to a piece of data from a MySQL database

$PartNo=mysql_result($result,$i,"PartNo");

Where

 $result = mysql_query("SELECT * FROM PriceList"); 

$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name

I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:

$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");

But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)

$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");

foreach ($nDatabaseVars as $X) {
    $$X=mysql_result($result,$i,'$X');
}

I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")

If I echo it out instead:

foreach ($nDatabaseVars as $X) {
    echo "$$X=mysql_result($result,$i,'$X')";
}

I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.

share|improve this question

2 Answers

up vote 2 down vote accepted

You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:

$$X=mysql_result($result, $i, $X);
share|improve this answer
Legends, thank you both. I was looking in the complete wrong spot. – Trav Easton May 8 '12 at 0:02
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.

$$X=mysql_result($result,$i,"$X");
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.