Page 1 of 1

Creating a variable on the fly

Posted: Thu Oct 17, 2002 9:25 am
by WillowFae
I need to loop through a sql update statement. The fields in the form have been given names with a number on the end depending on the ID in the table.
eg - foret1 on the first row, foret2 on the second.

To do the loop I am going to use a while loop and set $i to be 1 before the loop starts, increasing it each iteration of the loop.

But before I can even get that far I am having problems getting the value of the field from the form. Once I submit the form if I just output the value of $foret1 then I get the correct value. However, I need to generate the number to go on the end of this variable using $i. I have tried the following but it doesn't work.

echo($foret.$i);

I've also tried

echo($(foret.$i));

Infact I was getting so frustrated I was ending up trying ANYTHING :(

Any ideas?

Posted: Thu Oct 17, 2002 10:07 am
by Phirus
show us some code to get the full picture

Phirus

Posted: Thu Oct 17, 2002 10:08 am
by twigletmac

Posted: Thu Oct 17, 2002 10:15 am
by WillowFae
Twigletmac,

That's great, it worked, thanks :)

How would I use that in the sql statement

$query = "update price_test set foret='${'foret'.$i}' etc

Surely the ' before foret will be treated as the closing ' for the one before?

(sorry, I'm new to php)

Posted: Thu Oct 17, 2002 10:49 am
by d3ez
you could always generate that value first:

$val = ${'foret'.$i}

and then:

$sql = "update table set x='$val'...etc....

maybe that would work

Posted: Thu Oct 17, 2002 10:58 am
by WillowFae
Yeah, I thought of that and did the following (displaying the variable just to check it works)

$foretprice= ${'foret'.$i};
echo("$foretprice");

but it isn't displaying the value :(

Posted: Thu Oct 17, 2002 11:40 am
by Coco
try this instead?

$temp = foret . $i;
--------
echo $$temp

Posted: Thu Oct 17, 2002 1:01 pm
by twigletmac
You don't need a temporary variable, try:

Code: Select all

$query = "update price_test set foret='".${'foret'.$i}."'";
Mac

Posted: Fri Oct 18, 2002 2:47 am
by WillowFae
I'm now getting a parse error on that line. The full line of code I have is

$query = "update price_test set foret='".${'foret'.$i}."'" where priceID = $i;

Plus (and I'm still learning so trying to understand why things are in the code rather than just accepting that they are) I understand about adding the double quotes to the line, but what purpose do the extra dots have before the first $ and after the } ?

Posted: Fri Oct 18, 2002 3:11 am
by mikeq
double quote missing at the end

$query = "update price_test set foret='".${'foret'.$i}."' where priceID = $i";

I have put the double quotes in bold so you can see them. If priceID is expecting a string then $i will need to be enclosed in single quotes '

It is a good idea to output your $query to the browser during testing so you can see if it is what you expect

print "The query is $query";[/b]