I'm trying to send an HTML email receipt from a shopping cart purchase but I don't get how to echo the session array within the EOF area. php doesn't seem to want to execute here. Thoughts?
//begin of HTML message
$message = <<<EOF
<html>
<body style="font-family: 'Myriad Pro', 'DejaVu Sans Condensed', Helvetica, Arial, sans-serif;
font-size:10px;"><center>
<table width="750" cellpadding="0" cellspacing="0" class="view-cart" style="text-
align:center;padding:5px;"><tr>
<tr><td>Image</td><td>SKU</td><td>Description</td><td>QTY</td><td>Price</td><td> </td></tr>
<tr>
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<td><img src="'.$cart_itm['image'].'"></td>';
echo '<td>';
echo '<div class="p-code">'.$cart_itm["code"].'</td>';
echo '<td align="left">'.$cart_itm["description"].'</td>';
echo '<td>'.$cart_itm["qty"].'</td>';
echo '<td><div class="p-price">'.$cart_itm["price"].' each</div></td>';
echo '<td></td>';
echo '</tr>';
}
</table>
</center>
</body>
</html>
EOF;
//end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
mail($to, $subject, $message, $headers);
The updated code now looks like this. I replaced the "$message +=" with "$message .=" and it seems to work fine now. :
//begin of HTML message
$message = <<<EOF
<html>
<body style="font-family: 'Myriad Pro', 'DejaVu Sans Condensed', Helvetica, Arial, sans-serif; font-size:10px;"><center>
<table width="750" cellpadding="0" cellspacing="0" class="view-cart" style="text-align:center;padding:5px;">
<tr><td>Image</td><td>SKU</td><td>Description</td><td>QTY</td><td>Price</td><td> </td></tr>
<tr>
EOF;
foreach ($_SESSION["products"] as $cart_itm)
{
$message .= "<td><img src=".$cart_itm['image'].">";
$message .= "</td><td>".$cart_itm['code'];
$message .= "</td><td>".$cart_itm['description'];
$message .= "</td><td>".$cart_itm['qty'];
$message .= "</td><td>".$cart_itm['price'] ;
$message .= "each</td><td></td></tr>";
}
$message2 = <<<EOF
</table>
<hr><table width="750" cellpadding="0" cellspacing="0" class="view-cart"><tr>
<td align="right"><b>Shipping: $ $shipping </b><br><b>Total: $ $total </b></td></tr></table>
</center>
</body>
</html>
EOF;
What you're doing is creating a string using the heredoc syntax; so everything that's after the first newline and before the identifier (EOF in your case) is considered part of that string, and no code will be executed inside of it besides variables and escape sequences for special characters.
As far as I know there is no solution besides ending the string just before the loop, then replacing all instances of echo with $message += in the loop and finally creating a new string (using heredoc or conventional quotes and escaped newlines) after the loop and appending that new string to the $message.
Another (bad in my opinion) approach would be to put a placeholder for the loop's contents in the heredoc, then creating a new string that will hold the output of the loop and finally replacing the placeholder with that string.
Edit: for your updated code, note that the identifier EOF1 should be at the beginning of a new line and be terminated with a semicolon.
Also, the identifiers aren't supposed to be unique, it's fine to use the same identifier for different strings, no need for EOF1, 2, etc.
Related
The below code gives the output as how in screenshot. I want to send this content via php mail function . When i try to add this code into $message , It doesnt work as it contains php code(to retrieve data from table) in between html code. Kindly help on how this can be achieved ?
This is the code i was trying out for email .
<?php
include('db.php'); //connection to database
$to = 'example#gmail.com';
$subject = "test php mail" ;
$message = '
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta charset="utf-8">
<title> Fetching data </title>
</head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th{
color:#DC143C;
}
td {
color:#0000FF;
}
</style>
<body>
<font size="4" face="Courier New" >
<table border="1" style="width:50%" align="center">
<tr bgcolor="#2ECCFA">
<th style="padding: 20px" bgcolor="#E6E6FA"
color="#DC143C" color="red">Word of the Day</th>
</tr>
<!-- I used while loop to fetch data and display rows of date on html
table -->
<?php
$records = mysql_query("SELECT * FROM hindiday order by
rand(curdate())
limit 1 ");
while ($course = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$course['hindiword'] . ' ' .$course['phonetic'] . ' '
.$course['id']." </td>"; "</tr>" ;
}
?>
</table>
</body>
</html> ' ;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: abc#gmail.com.com>' . "\r\n";
// Send email
if(mail($to,$subject,$message,$headers)):
$successMsg = 'Email has sent successfully.';
else:
$errorMsg = 'Email sending fail.';
endif;
?>
I would suggest looping outside the string, and the concatenate the result like so :
$string = ''; // The variable used to contain your data
$records = mysql_Something is wrong("SELECT * FROM hindiday order by rand(curdate()) limit 1 ");
while ($course = mysql_fetch_assoc($records)){
//Filling that variable
$string .= "<tr>";
$string .= "<td>".$course['hindiword'] . ' ' .$course['phonetic'] . ' ' .$course['id']." </td>"; "</tr>" ;
}
//Using the variable in your message
$message = '
...
'. $string .'
...
';
That way wherever you want to add the $string you just concatenate it, as if you try to execute PHP code inside a string it'll be considered as a string and the PHP in question won't be executed.
So the final result would look like this :
<?php
include('db.php'); //connection to database
$to = 'example#gmail.com';
$subject = "test php mail" ;
$string = ''; // The variable used to contain your data
$records = mysql_Something is wrong("SELECT * FROM hindiday order by rand(curdate()) limit 1 ");
while ($course = mysql_fetch_assoc($records)){
//Filling that variable
$string .= "<tr>";
$string .= "<td>".$course['hindiword'] . ' ' .$course['phonetic'] . ' ' .$course['id']." </td>"; "</tr>" ;
}
$message = '
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta charset="utf-8">
<title> Fetching data </title>
</head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th{
color:#DC143C;
}
td {
color:#0000FF;
}
</style>
<body>
<font size="4" face="Courier New" >
<table border="1" style="width:50%" align="center">
<tr bgcolor="#2ECCFA">
<th style="padding: 20px" bgcolor="#E6E6FA"
color="#DC143C" color="red">Word of the Day</th>
</tr>
<!-- I used while loop to fetch data and display rows of date on html
table -->
'. $string .'
</table>
</body>
</html> ' ;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: abc#gmail.com.com>' . "\r\n";
// Send email
if(mail($to,$subject,$message,$headers)):
$successMsg = 'Email has sent successfully.';
else:
$errorMsg = 'Email sending fail.';
endif;
?>
I have a page where users select a product (products come from sql database) and input a quantity needed. They then view a "cart" page and submit the order which just sends a email to me with the details. I am trying to automatically update the quantity in the sql database when they submit the order.
I think I would have to do something like the following, but I am new to php and sql. I would have to take the original quantity from the DB and subtract the "ordered quantity" which is entered by the user and displayed on the cart page and set that new value. Can anyone shed some light on how I might accomplish this?
What I think I have to do?:
$updquery = 'UPDATE "products" SET "Quantity"= "Quantity" - '. $product['quantity'] .' WHERE PID = '. $product['id'] .' ';
cart.php
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<?php
#session_start();
if(isset($_POST['logout'])) {
unset($_SESSION['shopping_cart']);
}
if(isset($_POST['submit'])) {
$email = $_POST['email'];
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the ''
replacing yourname#yourdomain.com - This is where the form will send a
message to.
$email_subject = "Products Order - ".$_POST['email']."";
// PREPARE THE BODY OF THE MESSAGE
$email_body = '<html><body>';
$email_body .= '<h1 style="text-align:center;">Products List</h1>';
$email_body .= '<table rules="all" style="border-color: #666;margin:
auto;" border="1" cellpadding="10">';
$email_body .= '<tr><th colspan="2"><h3>Requested Parts</h3></th>
</tr>';
$email_body .= '<tr><th width="100" align="left">Product ID</th><th
width="100" align="right">Quantity</th></tr>';
foreach($_SESSION['shopping_cart'] as $key => $product):
$email_body .= '<tr><td>'. $product['id'] .'</td><td
align="right">'. $product['quantity'] .'</td></tr>';
endforeach;
$email_body .= "</table>";
$email_body .= "</body></html>";
$headers = "From: myemail#gmail.com\n"; // This is the email address
the generated message will be from. We recommend using something like
noreply#yourdomain.com.
$headers .= "Reply-To: ".$_POST['email']."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "X-Mailer: PHP/".phpversion();
mail($to,$email_subject,$email_body,$headers);
unset($_SESSION['shopping_cart']);
?>
<script>
alert("Your order has been submitted")
window.location.href = "index.php"
</script>
<?php
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Inventory Cart</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/icon.ico" type="image/x-icon">
<style>
*{
margin :auto;
}
table {
border-collapse: collapse;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
tr:nth-child(even) {
background-color: #eee;
}
tr:nth-child(odd) {
background-color: #fff;
}
</style>
</head>
<body>
<h1 style="text-align:center;">Cart</h1>
<?php
if(!empty($_SESSION['shopping_cart'])){ ?>
<div class="table-responsive" style="background:white;">
<table class="table table-responsive" id="mytable" border="1"
align="center">
<tr><th colspan="2"><h3>Requested Parts</h3></th></tr>
<tr>
<th width="100" align="left">Product ID</th>
<th width="100" align="right">Quantity</th>
</tr>
<?php
foreach($_SESSION['shopping_cart'] as $key => $product):
?>
<tr>
<td><?php echo $product['id']; ?></td>
<td align="right"><?php echo $product['quantity']; ?></td>
</tr>
<?php
endforeach;
?>
</table>
<div style="text-align:center;">
<form action="" method="post">
<input type="email" size="31" name="email" placeholder="Please enter
your email address" required /><br>
<input type="submit" name="submit" value="Submit" id="btnSubmit"/>
</form>
<form action="" method="post">
<input type="submit" name="logout" value="Clear" id="btnClear" />
</form>
</div>
</div>
<?php
}
else{
?>
<script>
alert("Cart is empty")
window.location.href = "index.php"
</script>
<?php
}
?>
<br><br>
</body>
</html>
You provided your own answer (query):
1) Set up mysql connection in the beginning of your script:
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
2) In your foreach, add the query to update each os the product's quantity as you add them to the e-mail. Becomes:
foreach($_SESSION['shopping_cart'] as $key => $product):
$email_body .= '<tr><td>'. $product['id'] .'</td><td align="right">'. $product['quantity'] .'</td></tr>';
mysqli_query($con,'UPDATE products SET Quantity = Quantity - '. $product['quantity'] .' WHERE PID = '. $product['id'] .' ');
endforeach;
mysqli_close($con);
Here is a small snippet of the PHP-Code I use to create a HTML e-mail:
$tmpl = '<table border="0" width="100%";><tr><td>%title%</td></tr><tr><td>%text%</td></tr></table>';
$html = '<table border="0" width="100%";>';
$html .= '<td width="20%" style="padding:0;">';
if(isset($var)) {
$html .= 'Value: '.$object->val;
}
$html .= '</td>';
$html .= '</table>';
$tmpl = str_replace('%text%', $html, $tmpl);
$mail->setBody( $tmpl );
$mail->send();
Sometimes the mail in the HTML view when viewed inside an email program is broken because there is a space character inside an opening TD-Element. Like this:
< td width="20%" style="padding:0;">
Where is this space character coming from?
Had the same issue with php mail() function, my html styling was broken by seemingly random spaces. Using wordwrap() on the message before sending it with mail sorted out the problem.
$message = wordwrap($message, 70);
mail("person#example.com","Some subject",$message);
www.w3schools.com explanation, example
See this line here?
$html = '<table border="0" width="100%";>';
after width="100%" you do not need this symbol -> ;
Try removing it.
Markup has errors
$tmpl = '<table border="0" width="100%";><tr><td>%title%</td></tr><tr><td>%text%</td></tr></table>';
Notice the ; in border="0" width="100%";>
You're not concatenating $html
The following line overwrite the table built up earlier
$html = '</table>';
You need to change that to;
$html .= '</table>';
Suggested actions
I would suggest echoing the body of the mail, and validating it with w3.
Have a read...
Concatenating
Validate your markup
<?php
$tmpl = '
<table border="0" width="100%">
<tr>
<td>%title%</td>
</tr><tr>
<td>%text%</td>
</tr>
</table>';
$html = '<table border="0" width="100%">';
$html .= '<td width="20%" style="padding:0;">';
if(isset($var)) {
$html .= 'Value: '.$object->val;
}
$html .= '</td>';
$html .= '</table>';
//Debug:
// echo $html;
$tmpl = str_replace('%text%', $html, $tmpl);
$mail->setBody( $tmpl );
$mail->send();
I have a PHP script through which I send HTML emails. I'm using a 'for' loop to collect data and storing it in a variable. The loop is instructed to run 25 times. The problem is that it is looping only 19 times. I checked for any unlcosed tags or typos in syntax but didn't find any. I'm posting the for loop section in case any of you can spot what I couldn't. It is really frustrating as I think the solution is very simple and yet I'm unable to spot the problem.
My headers for the 'mail()' function are fine. Here they are just in case
$headers = "From: $from \r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
And here is my for loop:
$abc ="<table width='600'>";
$abc .= "<tr>
<td bgcolor='#d6bf86'><span style='color:#9c2a00'>Number of Products</span></td>
<td align='center' bgcolor='#fde4d0'>$pagess</td>
<td align='center' bgcolor='#c3deb9'>$pagese</td>
<td align='center' bgcolor='#bee7f8'>$pagesu</td>
</tr>";
for($i=1; $i<=25; $i++)
{
$abc .="<tr>";
if($i % 2 == 0) // EVEN ROW
{
$abc .= "<td bgcolor='#d6bf86' width='260'><span style='color:#9c2a00'>".${f.$i}."</span></td>";
}
else // ODD ROW
{
$abc .= "<td bgcolor='#fffbd0' width='260'><span style='color:#9c2a00'>".${f.$i}."</span></td>";
}
if(isset(${s.$i}))
{
$abc .= "<td bgcolor='#fde4d0' align='center'>Yes</td>";
${s.$i} = "Yes";
}
else
{
$abc .= "<td bgcolor='#fde4d0' align='center'>No</td>";
${s.$i} = "No";
}
if(isset(${e.$i}))
{
$abc .= "<td bgcolor='#c3deb9' align='center'>No</td>";
${e.$i} = "Yes";
}
else
{
$abc .= "<td bgcolor='#c3deb9' align='center'>Yes</td>";
${e.$i} = "No";
}
if(isset(${u.$i}))
{
$abc .= "<td bgcolor='#bee7f8' align='center'>No</td>";
${u.$i} = "Yes";
}
else
{
$abc .= "<td bgcolor='#bee7f8' align='center'>Yes</td>";
${u.$i} = "No";
}
$abc .="</tr>";
}
if(isset($_POST['dscs'])) // DISCOUNT HAS BEEN APPLIED
{
$abc .= "<tr>
<td>Base Price</td>
<td align='center'>$sums</td>
<td align='center'>$sume</td>
<td align='center'>$sumu</td>
</tr>";
$abc .= "<tr>
<td>Discount Offered</td>
<td align='center'>$discount% </td>
<td align='center'>$discount% </td>
<td align='center'>$discount% </td>
</tr>";
$abc .= "<tr>
<td>Effective Price</td>
<td align='center'>$dscs</td>
<td align='center'>$dsce</td>
<td align='center'>$dscu</td>
</tr>";
}
else
{
$dscs = $sums;
$dsce = $sume;
$dscu = $sumu;
$abc .= "<tr>
<td>Total Price</td>
<td align='center'>$sums</td>
<td align='center'>$sume</td>
<td align='center'>$sumu</td>
</tr>";
}
$abc .="</table>";
I can attach the screenshot of the email that is being sent to give an idea on how the code is breaking. Let me know if you want the screenshot too.
PS : I copy-pasted this code in a separate file and ran it and it was working fine. The loop iterated 25 times. This makes me believe that there is a problem putting it inside HTML email.
Also adding in the email script if that helps:
$to = $clem;
$subject = "Something goes here";
$message = "<html>
<head></head>
<body style='background-color:#ffffff; font-family:Lucida Sans Unicode, Lucida Grande, sans-serif;'>
<table width='600'>
<tr>
<td>$abc</td>
</tr>
</table>
</body>
</html>";
$from = "$logged_user";
$headers = "From: $from \r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$res=mail($to,$subject,$message,$headers);
Thanks in advance,
Nisar
Nevermind, I found what was wrong. Here it is for people with similar problems.
I learnt that html emails have a 990 character limit per line. That was the reason why my code was breaking
I'm trying to send an email to myself that has a layout and images. What I'm I doing wrong?
<?php
$message = $_POST['message'];
$emailsubject = 'site.com';
$webMaster = 'email#site.com';
$body = "
<html>
<body bgcolor=\"e7e7e7\">
<style type=\"text/css\">
#body {margin: auto;border: 0;padding: 0;font-family: Georgia, 'Times New Roman', Times, serif;font-size: 12px;}
#emailHeader {width: 500px;height: 131px;background: url(http://www.site.com/images/image.gif) no-repeat;}
#emailContent {width: 500px;background: url(http://www.site.com/images/image2.gif) repeat-y;text-align: left;padding: 0 33px 0 6px;}
#emailFooter {width: 500px;height: 34px;background: url(http://www.site.com/images/image3.gif) no-repeat;}
</style>
<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
<tr>
<td valign=\"top\" align=\"center\">
<table width=\"500\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
<tr>
<td id=\"emailHeader\"></td>
</tr>
<tr>
<td id=\"emailContent\">
content $message
</td>
</tr>
<tr>
<td id=\"emailFooter\"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>"
$headers .= "Content-type: text/html\r\n";
$success = mail($webMaster, $emailsubject, $body, $headers);
if ($success) {
echo "Your message was sent.";
}
else{
echo "There was a error.";
}
?>
You should use phpmailer instead of PHP's mail()-Function. It allows you to easily send HTML-Mails.
Besides that you can try to validate your HTML-Code to be compatible for emailing.
Best wishes,
Fabian
You have an error in your code:
WRONG
$headers .= "Content-type: text/html\r\n";
RIGHT
$headers = "Content-type: text/html\r\n";
The .= throws a parse error in PHP unless you previously set $headers somewhere else.
It also may depend on the email client you are testing with. Be sure to check out http://www.email-standards.org/ to check what your email client supports.
You may also want to look into Zend_Mail from Zend Framework:
http://framework.zend.com/manual/en/zend.mail.html
Would make dealing with headers, formats, MIME, etc. easier.