Jump to content

Arrays and loops HELP


Harley1979

Recommended Posts

The following code is looping through a database to write out an shopping cart order into an array.

 

How can I display the array outside of the loop elsewhere in my page without having to do things within the same loop?

 

For instance:

foreach ($product as $key => $value) {

 

$select = mysql_query("SELECT * FROM products WHERE  id  = $key);

while($row = mysql_fetch_array($select)){

 

$i += 1;

$basket[$i] = $qty." x ".$row['item']." £".$row['price'];

 

}

}

 

Any help would be greatly appreciated

 

Thanks

 

P

Link to comment
Share on other sites

in order to use the array in elsewhere, you must define the array as global variable .

 

No it doesn't.

 

How can I display the array outside of the loop elsewhere in my page without having to do things within the same loop?

 

<?php

  foreach($basket as $v => $k) {
    echo $v . ' = ' . $k . "<br />";
  }

?>

Link to comment
Share on other sites

<?php

$select = mysql_query('SELECT * FROM products WHERE id IN (' . implode(',',array_keys($product)) . ')');
if ($select && mysql_num_rows($select)) {
$basket = array();
while ($row = mysql_fetch_assoc($select)) $basket[] = "$qty x $item £$price";
}

 

How can I display the array outside of the loop elsewhere in my page without having to do things within the same loop?

 

Things?  I'm not sure what you mean by "things."  You've already use foreach().  You can use it again later, too.

Link to comment
Share on other sites

<?php

 

  foreach($basket as $v => $k) {

    echo $v . ' = ' . $k . "<br />";

  }

 

?>

 

This is my problem, I can write out the array whilest looping through the db using a foreach loop no sweat, but outside I will only get results of the last row in the database which is not what I want.

 

Setting a global array sounds much more promising, does anyone know of any good tutorials?

Link to comment
Share on other sites

Try this:

 

<?php
$basket = array();
$select = mysql_query('SELECT * FROM products WHERE id IN (' . implode(',',array_keys($product)) . ')');
if ($select && mysql_num_rows($select)) while ($row = mysql_fetch_assoc($select)) $basket[] = "$qty x $item £$price";

echo '<pre>',print_r($basket,true),'</pre>';

 

How can I display the array outside of the loop elsewhere in my page without having to do things within the same loop?

 

Things?  I'm not sure what you mean by "things."  You've already use foreach().  You can use it again later, too.

Link to comment
Share on other sites

Ok, I've tried that and it looks that it will almost work, I'm just not sure what it is I'm doing wrong. This is now my code, and below is what is echoed to the screen.

 

foreach ($product as $key => $value) {

if ($value!='') {

$basket = array();
$select = mysql_query("SELECT * FROM products WHERE id = $key");

if ($select && mysql_num_rows($select)){
while ($row = mysql_fetch_assoc($select)) $basket[] = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$price).", ";
}
}

 

and this is what I get:

 

Array

(

    [0] =>  x 1 £0.00,

)

 

Array

(

    [0] =>  x 1 £0.95,

)

 

Thanks

 

 

Link to comment
Share on other sites

Wow that is bad coding try this out instead

 

<?php
foreach ($product as $key => $value) {
if ($value!='') {
             $in = "'" . $key . "',";
        }	
}

$in = substr($in, 0, -1);

$select = mysql_query("SELECT * FROM products WHERE id IN(" . $in . ")");

if (mysql_num_rows($select) > 0){
while ($prodRow = mysql_fetch_assoc($select)) {
             $basket[] = $prodRow['item']." ".$prodRow['size']." x ".$product[$prodRow['id']]." £".money_format('%.2n',$price).", ";
         }

        echo '<pre>', print_r($prodRow), '</pre>';
}
?>

 

My confusion on this is where is where does $price come from. Either way that is a lot better than previous as it just uses 1 sql statement to gather the data instead of like 10 etc.

Link to comment
Share on other sites

Ok, to reiterate after tonights php brain melting session; I am successfully writing out a string which basically records a users journey through the shopping cart which I can write into my database for future use incase the user needs to know what they have ordered.

 

Now that I have this string whilest still inside the "while loop", how can I output it outside the loop?

 

$product = unserialize($_SESSION['product']);

foreach ($product as $key => $value) {

if ($value!='') {
$basket = array();
$select = mysql_query("SELECT * FROM products WHERE id IN ($key)");
if ($select && mysql_num_rows($select)){
while ($prodRow = mysql_fetch_assoc($select))
	$basket = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$prodRow['price']).", ";
}

$insertBasket = print_r($basket,true);

}
}

//insert into wholefoods_orders db all other info
mysql_query("INSERT INTO wholefoods_orders (date, basket, total, refID, title, name, address1, address2, street, town ,city, postcode, tel, email, medium) VALUES ('$insertDate', '$insertBasket', '$insertTotal', '$getRefID', '$insertTitle', '$insertName', '$insertAddress1', '$insertAddress2', '$insertStreet', '$insertTown', '$insertCity', '$insertPostcode', '$insertTelephone', '$insertEmail', '$insertMedium')") or die(mysql_error());  

 

Any ideas on how I can achieve this? Obviously when I write out $insertBasket outside the loop it only returns the last item

 

Thanks

 

Link to comment
Share on other sites

change

$basket = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$prodRow['price']).", ";

to

$basket[] = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$prodRow['price']).", ";

Link to comment
Share on other sites

change

Code:

$basket = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$prodRow['price']).", ";

to

Code:

$basket[] = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$prodRow['price']).", ";

 

This still returns only the last row in the database though. How do I use $basket[] to write out my string outside the loop?

Link to comment
Share on other sites

Your code is a bit crazy.  (1) the SQL query is inefficient, (2) why are you assigning the print_r value to a variable and trying to insert it into the database? (3) Don't use "IN()" for single values; use "=".

 

You're querying the database for each individual value.  From other things you've posted, I'm assuming(?) that you have all of the product IDs in an array, $product.  Is that correct?  If so, instead of looping through each product value, you can simplify and increase efficiency by querying for all the values at one time.  For example, you can join the values of $product into a comma-delimited string like so:

 

// If the array is just values, like $product = array(101,335,902);
$product_string = implode(',',$product);
// Would equal "101,335,902"

// Or, if the product IDs are keys,
// like $product = array(101 => '',335=>'',902=>'');
$product_string = implode(',',array_keys($product));
// Would equal "101,335,902"

 

Now you can put that into a query involving the "IN()" function.

 

$select = mysql_query("SELECT * FROM products WHERE id IN ($product_string)");
// The query will be: "SELECT * FROM products WHERE id IN (101,335,902)"

 

And you only need to loop through the results instead of making a single query every time.

 

$basket = array();
if ($select && mysql_num_rows($select)){
while ($prodRow = mysql_fetch_assoc($select))
	$basket[] = $prodRow['item']." ".$prodRow['size']." x ".$value." £".money_format('%.2n',$prodRow['price']).", ";
}

 

The "[]" at the end of $basket means "append the following to the array $basket."  If you omit that, $basket becomes a string, not an array, and gets overwritten each time.

Link to comment
Share on other sites

Thanks for the advice, I've got things running smoother now.

 

I have now re-writen my code to this:

 

$product = unserialize($_SESSION['product']);

foreach ($product as $key => $value) {

if ($value!='') {

$select = mysql_query("SELECT * FROM products WHERE id IN ($key)");

$basket = array();
if ($select && mysql_num_rows($select)){
	while ($prodRow = mysql_fetch_assoc($select))
		$basket[] = $prodRow['item']." ".$prodRow['size']." x ".$value." ".money_format('%.2n',$prodRow['price']).", ";

}
}
}

// need to write out $basket here

 

Still using the

WHERE id IN ($key)

as this holds my id's in an array.

 

I can echo $basket inside the loop fine and everything displays as it should.

 

Just not sure of how to echo $basket outside of the loop, how can I store all the rows in one variable that can repeated anywhere in my page?

 

Thanks

Link to comment
Share on other sites

try

<?php
$product = unserialize($_SESSION['product']);
$basket = array();
foreach ($product as $key => $value) {
if ($value!='') {
	$select = mysql_query("SELECT * FROM products WHERE id = '$key'");
	if ($select && mysql_num_rows($select)){
		while ($prodRow = mysql_fetch_assoc($select)) {
			$basket[] = $prodRow['item']." ".$prodRow['size']." x ".$value." ".money_format('%.2n',$prodRow['price']).", ";
		}	
	}
}
}

// need to write out $basket here
foreach ($basket as $value) echo $value, "<br />\n";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.