0

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.

2 Answers 2

2

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);
1
  • Legends, thank you both. I was looking in the complete wrong spot. Commented May 8, 2012 at 0:02
0
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.