Jump to content

Dynamic Varables Names


mclamais

Recommended Posts

I'm a PHP newbie, I need to assign query results to variables that have an incrementing number in the variable name, can someone help me with this?

 

So let say I return a few rows of from MySQL, I would like loop though the results and assign the values to variables with incrementing numbers like the following:

 

while($row1 = mysql_fetch_assoc($result1)) {
$sku_[color=red]1[/color] = row1["sku"];
$quantity_[color=red]1[/color] = row1["quantity"];
};

 

while($row1 = mysql_fetch_assoc($result1)) { $sku_1 = row1["sku"]; $quantity_1 = row1["quantity"]; };

 

where 1 is the incrementing

 

I eventually need to put these results into a URL like this

&sku_1=1234&quantity_1=1
&sku_2=1235&quantity_2=1
&sku_3=1236&quantity_3=2

 

Thanks,

 

Marc

Link to comment
https://forums.phpfreaks.com/topic/104247-dynamic-varables-names/
Share on other sites

Try this

<?php
while($row1 = mysql_fetch_assoc($result1)) {
$skus[$row1["sku"]] = $row1['quantity'];
}
$link = "http://mydomain.com/page.php?";
$i = 1;
foreach($skus as $sku => $quantity){
$link .= "sku_$i=$sku&quantity_$i=$quantity&";
$i++;
}
$link = substr($link, 0, -1);
echo $link;
?>

 

Ray

 

While I agree with Craygo,  I do not presume to know why you are doing it this way, but to accomplish what you asked, it can be written:

 



<?php
while($row1 = mysql_fetch_assoc($result1)) {
$sku="sku_[color=red]1[/color]";
             $$sku = row1["sku"];
$quanitity = "quantity_[color=red]1[/color]";
             $$quantity = row1["quantity"];
};
?>

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.