Door
Alex van Dijk
op 29-07-2012 13:24
gewijzigd op 29-07-2012 13:34
1.655 views
Beste mensen,
De afgelopen tijd ben ik druk bezig geweest met het maken van een webwinkel maar ik ben een vervelend probleem tegen gekomen bij het mailen van de factuur. Als ik namelijk 'de winkelwagen' wil mailen stuurt het script voor elk product een aparte mail.
Ik probeer het volgende te mailen:
<?php
$get_row['name'].' '.$value.' stuk(s) prijs €'.number_format($get_row['price'], 2).' = €'.number_format($sub, 2);
?>
Oohja sorry helemaal vergeten. Ik verstuur mijn mail met phpmailer.
De code:
<?php
if (isset($_POST['Submit'])) {
foreach($_SESSION as $name => $value){
if ($value>0){
if(substr($name, 0, 5)=='cart_'){
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
require_once('PHPMailer_5.2.1/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.website"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.website"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "sales@website"; // SMTP account username
$mail->Password = "wachtwoord"; // SMTP account password
$mail->AddReplyTo('sales@lwebsite', 'First Last');
$mail->AddAddress("[email protected]");
$mail->SetFrom('sales@website', 'First Last');
$mail->AddReplyTo('sales@website', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->Body = $get_row['name'].' '.$value.' stuk(s) prijs €'.number_format($get_row['price'], 2).' = €'.number_format($sub, 2);
$mail->IsHTML(true);
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
de while op regel 8 zorgt ervoor dat $get_row leeg is, en is niet nodig omdat maar 1 record terug krijgt.
Maar je moet de de body van de mail in die foreach daar samenstellen.
Ik zou trouwens ook van de $_SESSION['cart'] een array maken, met het product id als key het aantal als value
?
Onbekende gebruiker
29-07-2012 22:31
gewijzigd op 29-07-2012 22:43
Ik zou eerst en vooral zoals Ger van Steenderen zegt een $_SESSION['cart'] maken. Dus het voorbeeld hieronder toon hoe het moet met een $_SESSION['cart'].
Er kunnen wel errors inzitten omdat ik het gewoon even geschreven heb en dus laat ik het even aan u over om het allemaal te testen.
Als u het script dat hieronder staat dan nog even aanpast met een goede query afhandeling en het verzenden van een mail moet het normaal lukken. Tevens raad ik ook mysql_ af, daarvoor hebben we nu de vervanger mysqli, PDO of een andere database driver.
<?php
/**
* When the user posted the form, we'll run the hole code and
* send an email:
*/
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])) {
/**
* When the cart array exists, we are going to check everything, else
* we show an error:
*/
if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {
/**
* Run true all the sessions and catch those with cart_ as
* the first letters. But first make a var with all the ids of
* the articles:
*/
$ids = '';
foreach($_SESSION['cart'] as $name => $value) {
if(strlen(preg_replace('/[^0-9]/', '', $name)) > 0 && strlen(preg_replace('/[^0-9]/', '', $value)) > 0) {
$ids .= '"'.preg_replace('/[^0-9]/', '', $name).'",';
$_SESSION['cart'][preg_replace('/[^0-9]/', '', $name)] = preg_replace('/[^0-9]/', '', $value);
}
}
/**
* When there aren't any ids found, then we are going to notice the
* user that he/she needs to select some products:
*/
if(strlen($ids) == 0) {
echo 'Please add some products to your cart.';
}
else {
/**
* Get all the records from the products in the database with the
* matching id:
*/
$result = mysql_query("SELECT id, name, price FROM products WHERE id IN(".substr($ids, 0, -1).")");
/**
* When there is a result, we are going to loop true it, otherwhise we'll
* notice the user:
*/
if($result != false) {
/**
* Check if there are some product. Otherwhise show and notification that the
* user need to add some products:
*/
if(mysql_num_rows($result) > 0) {
/**
* When there are some products found. Loop true them and show the information
* on the screen:
*/
while($row = mysql_fetch_assoc($result)) {
echo '<p><b>Product ID:</b> '.$row['id'].'<br /><b>Name:</b> '.$row['name'].'<br /><b>Price:</b> '.$row['price'].'<br />';
echo '<b>Total price:</b> '.$row['price'] * $_SESSION['cart'][$row['id']].'</p>';
}
}
else {
echo 'Please add some products.';
}
}
else {
/**
* Add some optionally error handling for the adminster. To make it easy
* to solve problems, but for the example just show a message:
*/
echo 'There went something wrong while selecting the products.';
}
}
}
else {
echo 'Please add some products to your cart.';
}
Bedankt Ger van Steenderen en Aaron, ik had die foreach helemaal over het hoofd gezien. Zouden jullie kunnen uitleggen waarom het handig is om een $_SESSION['cart']te maken, en Aaron waarom je mysql_ afraad?
[offtopic]De Nederlandse regering en heel veel milieu organisaties zouden daar hartstikke blij mee zijn ;-)
Ik zou trouwens PDO ook geen sportwagen willen noemen, maar meer een multifunctionele fiets met zijwieltjes.
[/offtopic]
Back to topic:
$_SESSION is een super global variabele van het type array, maar een array item kan ook weer een array zijn.
Dus op het moment dat iemand gaat bestellen maak je een $_SESSION['cart'] aan:
Daarna vul je die array met als key het product id en als waarde het aantal:
<?php
//als iemand 3 stukst product met id 345609 besteld
$_SESSION['cart'][345609] = 3;
// in php hoeven numerieke keys niet opeenvolgend te zijn!
?>
Even nog een heel belangrijke opmerking:
In je beginpost zeg dat je facturen via email verstuurt, let wel dat je die voor de belastingdienst op de een of andere manier moet kunnen reproduceren.