0

I am playing around with a PHP shopping cart and I am trying to send the order of the customer via email to the seller.

My problem is that if there are multiple items ordered, only the last one is actually sent in the email but when I echo, all the items are displayed.

Could you please explain why this is happening?

if(isset($_SESSION["products"])){
$total = 0;
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm){
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$rows = array();
while ($obj = $results->fetch_object()){

$rows[] = $obj; 

    echo $rows[0]->product_name.' x '.$cart_itm["qty"].' ; '; // here is ok

    $prod_name = ($rows[0]->product_name); // here only the last product displays. Why?!
}
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
$cart_items ++;

}
}

$prod_name = str_replace($cyr, $lat, $prod_name);

$random = rand(72891, 92729);
$subject = "New order #$random";        
$message = "You have new order from $name  $lname with adress $curraddr and order details: $prod_name with a total value of $total dollars.";   

$from = "From: admin@mail.xyz";
$to = "mail@mail.com";

mail($to, $subject, $message, $from);
Daniel
  • 10,641
  • 12
  • 47
  • 85
Thundermole
  • 59
  • 2
  • 9

1 Answers1

1

Every time you iterate through the while loop, you overwrite $prod_name. The last time through the loop, you overwrite the variable with the last product.

As for the echo "working," the output of the echo is not being overwritten every time you go through the loop. Instead, you are constantly appending to the end of what you printed last time.

To insert all product names into your email message, you should build the message as you go through the loop. Try reading about string concatenation to learn more.

Community
  • 1
  • 1
Jack
  • 2,750
  • 2
  • 27
  • 36
  • WOW thanks so much for the hint, I did not realise it was so simple. I just needed $prod_name .= $obj->product_name. ' x '.$cart_itm["qty"].' ; '; but I did not know I can do it with ".=" Thanks again ! – Thundermole Mar 03 '17 at 08:01