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_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

Recommended Answers

All 2 Replies

Hi Marc,

I had a look at this last night. Sorry I didn't post a reply then. But here is what I was thinking you could do.

If you create a multi-dimensional array within which you store the results from your query. The inner array would be indexed by the keys 'sku' and 'qty', although these could be anything.

$products = array();
$intC = 1;   // Integer counter to iterate through array.

while($row1 = mysql_fetch_assoc($result1)) {

$products[$intC] = array('sku' => row1["sku"], 'qty' => row1["quantity"]);
$intC++;

}

// For the output, you could then use a for loop. Or alternatively nested foreach loops. And you will be given an array indexed by an integer with each url string
$url = array();

for($i = 1; $i <= $intC; $i++) {
$url[$i] = "&sku_$i={$products[$i]['sku']}&quantity_$i={$products[$i]['qty']}";
}

If you provide a little more detail as to how you want to use the output, there might be a better solution for dealing with the construction of the url's.
Also, I noticed that you had a ; after the trailing while bracket. This is not required.

Hope this is helpful.

R

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_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

the way to declare vars with dynamic names is as follows.

$var1 = "hel";
$var2 = "lo";
$hello = "yo  there";

echo ${$var1.$var2};

output = "yo there";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.