php to mysql data retrieval - php

I am trying to retrieve data from mysql database that has 4 rows. I need to send this as an table in email using php. I have built a script for this, but the issue is the script is not emailing all the rows, its just emailing the last row or if i pass a specific parameter with "where" in db query.
Any help from anyone is appreciated. Thank you in advance.
Attached the db output and php code as well.
<?php
date_default_timezone_set('America/Los_Angeles');
$today = date("j-F-Y g:i:s a"); // March 10, 2001, 5:16 pm
// DB Connect.
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'test123#'; // Password
$db_name = 'util'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "select * from srvr1";
$result = mysqli_query($conn, $sql);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$File_system = $row[0];
$IP = $row[1];
$Capacity = $row[2];
$Available = $row[3];
$Used = $row[4];
$Percentage = $row[5];
# Compare Percentage and alert.
$subject = "Critical | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:red'> critical</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b><p>
<p>Regards, <br>
Backup Team. </p>
</body>
</html>";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
}
?>
I have been trying to shuffle around the loop in the code, it did not help.

Try and rearrange your code a little bit. First create the 'top' of the html, then go through all the results and append them to the html and then finish the html.
I haven't tested the code beneath but it should work :-)
<?php
date_default_timezone_set('America/Los_Angeles');
$today = date("j-F-Y g:i:s a"); // March 10, 2001, 5:16 pm
// DB Connect.
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'test123#'; // Password
$db_name = 'util'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "select * from srvr1";
$result = mysqli_query($conn, $sql);
if (!$result) {
die('SQL Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
$subject = "Critical | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:red'> critical</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
$File_system = $row[0];
$IP = $row[1];
$Capacity = $row[2];
$Available = $row[3];
$Used = $row[4];
$Percentage = $row[5];
# Compare Percentage and alert.
$message1 .= "
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td> $Percentage </td>
</tr>";
}
$message1 .= "</table>";
$message1 .= "<p style='font-size:15px'> Data generated at:<b> $today EST.</b><p>
<p>Regards, <br>
Backup Team. </p>
</body>
</html>";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
?>
About conditional formatting
No worries. You can try and use nested ternaries (shorthand for if/else... to keep it short :-))
Example snippet from above code:
...
$Percentage = $row[5];
$color = ($Percentage > 90) ? '#FCE901' : (($Percentage > 85) ? '#FF0000' : '#00E526');
# Compare Percentage and alert.
$message1 .= "
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td style=\"background-color:$color\"> $Percentage </td>
</tr>";

The issue is somewhere on your database end. Based on your var_dump output:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(6) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }
You only have 1 result being returned. You should start there. Maybe you're not referencing the table you think you are. Who knows right now, but you php looks fine. Investigate your DB

Your PHP is not fine stubben gave you the answer
<?php
date_default_timezone_set('America/Los_Angeles');
$today = date("j-F-Y g:i:s a"); // March 10, 2001, 5:16 pm
// DB Connect.
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'test123#'; // Password
$db_name = 'util'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn)
{
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = "select * from srvr1";
$result = mysqli_query($conn, $sql);
if (!$result)
{
die ('SQL Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$File_system = $row[0];
$IP = $row[1];
$Capacity = $row[2];
$Available = $row[3];
$Used = $row[4];
$Percentage = $row[5];
Above You have a Percentage from 1 Row of Data
Below you use that to decide the eMail subject - only 1 subject per email - so 1 row of data per email
# Compare Percentage and alert.
if($Percentage > 90)
{
$subject = "Critical | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<head>
<style>
body,h6 {
font-family: Segoe UI,Helvetica,courier;
}
th {
border: 1px solid black;
border-collapse: collapse;
background-color: #04D1E8;
padding: 10px;
text-align: center;
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
text-align: center;
}
.cri {
background-color: #FF0000;
}
</style>
</head>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:red'> critical</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td class='cri'> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b><p>
<p>
Regards, <br>
Backup Team.
</p>
</body>
</html>
";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
else if($Percentage > 85)
{
$subject = "Warning | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<head>
<style>
body,h6{
font-family: Segoe UI,Helvetica,courier;
}
th {
border: 1px solid black;
border-collapse: collapse;
background-color: #04D1E8;
padding: 10px;
text-align: center;
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
text-align: center;
}
.war {
background-color: #FCE901;
}
</style>
</head>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:yellow'> above normal</b>. Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td class='war'> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b></p>
<p>
Regards, <br>
Backup Team.
</p>
</body>
</html>
";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
else
{
$subject = "Normal | FH NetApp-NetBackup Space Utilization..!";
$message1 = "
<html>
<head>
<style>
body,h6{
font-family: Segoe UI,Helvetica,courier;
}
th {
border: 1px solid black;
border-collapse: collapse;
background-color: #04D1E8;
padding: 10px;
text-align: center;
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
text-align: center;
}
.nor {
background-color: #00E526;
}
</style>
</head>
<body>
<p> Hi Team,<br><br> The Server utilization is <b style='color:green'> normal. </b>Please find the below utilization details.</p>
<table>
<tr>
<th> File_System </th>
<th> IP </th>
<th> Total_capacity </th>
<th> Available_Capacity </th>
<th> Used_Capacity </th>
<th> Percentage </th>
</tr>
<tr>
<td> $File_system </td>
<td> $IP </td>
<td> $Capacity </td>
<td> $Available </td>
<td> $Used </td>
<td class='nor'> $Percentage </td>
</tr>
</table>
<p style='font-size:15px'> Data generated at:<b> $today EST.</b></p>
<p>
Regards, <br>
Backup Team.
</p>
</body>
</html>
";
$headers[] = 'From: Srvr19utilization#util.com'; // Sender's Email
$headers[] = 'Cc: santosh.kowshik20#gmail.com'; // Carbon copy to Sender
$headers[] = 'MIME-Version: 1.0 charset=".$encoding."';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message1, 70);
// Send Mail By PHP Mail Function
mail($to, $subject, $message, implode("\r\n", $headers));
}
}
}
?>

Related

unable to generate automail on daily bases

I am unable to generate auto mail on daily bases. The issue is it is not able to generate it automatically. Where as i have a same sort of code which does generates it everyday. With all the same details. The code is exactly same except the database query.
Here is my code:
<?php
session_start();
require("../connect.php");
/* require files for MAIL */
require("class.phpmailer.php");
require("class.smtp.php");
/* require files for MAIL ENDS */
/******** Get the list of audits done in week risk category falls under High Risk and during the previous visit also the location was under High risk category ----mail on every Saturday**********/
$current_date = date('Y-m-d');
//$current_date ='2015-08-22';;
/*$start_time = time() - (6*86400);
$start_dt = date('Y-m-d',$start_time);*/
$pagent_array = array();
$query="Select * from `location_details` ld
Left Join `answer_general_qc` ans_general on ans_general.lid=ld.id
Left Join `audit_general` general on general.qtno = ans_general.qt
Left Join `audit_general_option` general_opt on general_opt.opt_id = ans_general.ans_remark
where ld.completed ='1' and ld.priority != 'qc' and general.qtno ='1' and ans_general.opt = 'no' and
STR_TO_DATE(ld.`date_audited`,'%d-%m-%Y') = '".$current_date."'";
$result=mysql_query($query);
$th_style="border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede";
$td_style="border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff";
$table_result .="<table align='center' rules='all' style='font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;' border='1';>
<thead>
<tr>
<th style='".$th_style."'>Sr No</th>
<th style='".$th_style."'>Location Code</th>
<th style='".$th_style."'>Location Name</th>
<th style='".$th_style."'>PAgent</th>
<th style='".$th_style."'>Address 1</th>
<th style='".$th_style."'>Address 2</th>
<th style='".$th_style."'>District</th>
<th style='".$th_style."'>State</th>
<th style='".$th_style."'>Priority</th>
<th style='".$th_style."'>Remark by TO</th>
<th style='".$th_style."'>Remark by TO</th>
</tr>
</thead>
<tbody>";
$sr_no=1;
if(mysql_num_rows($result) != 0)
{
while($row=mysql_fetch_array($result))
{
if($row['option_text'] == "")
{
$option_text="Other";
}
else
{
$option_text=$row['option_text'];
}
$table_result .= "
<tr>
<td style='".$td_style."'>".$sr_no."</td>
<td style='".$td_style."'>".$row['location']."</td>
<td style='".$td_style."'>".$row['agent']."</td>
<td style='".$td_style."'>".$row['pagent']."</td>
<td style='".$td_style."'>".$row['address1']."</td>
<td style='".$td_style."'>".$row['address2']."</td>
<td style='".$td_style."'>".$row['district']."</td>
<td style='".$td_style."'>".$row['state']."</td>
<td style='".$td_style."'>".$row['priority']."</td>
<td style='".$td_style."'>".$option_text."</td>
<td style='".$td_style."'>".$row['qc_remark']."</td>
</tr>";
$sr_no++;
}
}
else
{
$table_result .="<tr><td colspan='9' align='center'>No Locations Found</td></tr>";
}
$table_result .="</tbody>
</table>";
// echo $table_result; exit;
/* Code to send MAIL */
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "host";
$mail->SMTPAuth = true;
//$mail->SMTPSecure = "ssl";
$mail->Port = 25;
$mail->Username = "Username";
$mail->Password = "Password";
$mail->From = "From";
$mail->FromName = "Name";
$mail->AddAddress("Email");
$mail->AddBCC("Email CC");
$body = "Dear All,<br /><br />For the review conducted on ".date('d-m-Y',strtotime($current_date))." in the following locations we have found deviation in question 1.1 (ie Does this location exist exactly at the address provided?) <br /><br /><br /><br />";
$body .= $table_result;
$body .= "<br /><br />Warm Regards <br /><br />
Note : Please do not reply to this email as this is an automated mail generated
";
//end body
$mail->IsHTML(true);
//$mail->Subject = "Ref : RC1/HR/".strtoupper($pa)."/".date('F Y',(time()-(5*86400)));
$mail->Subject = "Ref : Lrr 1.1 deviation";
$mail->Body = $body;
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
/* Code to send MAIL Ends */
//mail($to,$subject,$message,$headers);
echo 'Mail sent to '.$pa.'<br /><br />';
/****** END of sending mail **********/
?>
If you want to send mails on a regular or daily basis the ideal way to do that would be to use cron job for sending the mails.By using cron you can specify what application do you want the cron to run on.Also you will be able to specify what time exactly do you want the mail to be sent.
Refer here https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job .
Hope it helps.

How to add html table to database and save

I am new to PHP.I had created the table with the button "save Form".I am unable to save the table data to database.When I click on the "save form" button no action is performing.Please help me.
This is my Form.phtml
<div>
<b> Hello <?php echo $_POST["name"]; ?>!</b><br>
<b>Email :</b> <?php echo $_POST["email"]; ?>.<br>
<b>Gender :</b> <?php echo $_POST["gender"]; ?>.<br>
<b>Birthday :</b>
<?php
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$date = $day."-".$month."-".$year;
$myDate = date("d F Y", strtotime($date));
echo $myDate;
?>
</div>
<form action="sendmail.php" method="post" id="vaccination-form">
<div>
<table border="1" style="width:100%">
<tr>
<th id= "sno" style="font-family: sans-serif; font-size: 100%; font-weight: bold;" class="bg-color" width="5%">S.No</th>
<th id= "vaccine" style="font-family: sans-serif; font-size: 100%; font-weight: bold;" class="bg-color center" width="32%">Vaccine</th>
<th id="decsription" style="font-family: sans-serif; font-size: 100%; font-weight: bold;">Description</th>
<th id="duedate" style="font-family: sans-serif; font-size: 100%; font-weight: bold;" class ="bg-color" width="15%">Due Date</th>
</tr>
<tr>
<td>1</td>
<tr>
</table>
</form>
<div>
<button type="submit" name="submit" style="margin-top: 1cm;"title="<?php echo $this->__('Save Form') ?>" value="submit "class="button"><span><span><?php echo $this->__('Save Form')?></span> </span> </button>
</div>
sendmail.php
<?php
//due dates
$myDate=$_POST['myDate'];
$dueDate=$_POST['dueDate'];
$rodueDate=$_POST['rodueDate'];
$didueDate=$_POST['didueDate'];
$pdueDate=$_POST['pdueDate'];
$hadueDate=$_POST['hadueDate'];
$indueDate=$_POST['indueDate'];
$idueDate=$_POST['idueDate'];
$rdueDate=$_POST['rdueDate'];
$vdueDate=$_POST['vdueDate'];
$tdueDate=$_POST['tdueDate'];
$hdueDate=$_POST['hdueDate'];
$mdueDate=$_POST['mdueDate'];
$email=$_POST['email'];
$name=$_POST['name'];
$to=$email;
$subject= "Vaccination Schedule For ".$name;
$message=
'
</table>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers.= "From: someone#example.com" . "\r\n" ;
if( mail($to, $subject, $message, $headers))
{
echo 'Your mail has been sent successfully';
}
else
{
echo 'Unable to send email. Please try again.';
}
?>
Show us your sendmail.php.
Mainly you need to get POST variables into sendmail.php and then create a insert sql statement with data you got from POST variables..
How to do stuff above is totaly up to you, there are many ways, but we cannot tell you since you didnt give us enough info about your system.
I do not think the right thing to do , but still think you need to put the submit button between tags

PHPMailer MySQLi multiple email addresses

I am at the end of my rope and would really really appreciate any help you could spare...
I have the following code and although it works on an individual basis, I can for the life of me not make it work so that all email addresses are sent at the same time using PHPMailer.
I have scoured StackOverflow for the past few months, trying an exhaustive amount of combinations without success.
There are a number of discussions on this forum and although I have tried all the solutions on here, I can still not make it work. If I offend anyone by potentially duplicating the question, please accept my apologies in advance.
<?php
// Script Error Reporting
//error_reporting(0);
// Require the form_functions to process the form
require('databaseConnect.php');
// Require the Email Class Functions
require("mailApp/class.phpmailer.php");
require("mailApp/class.smtp.php");
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive=true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->setFrom("No_Reply#girrawaagames.com", "Girrawaa Games"); // Valid email address from sender and Company name. Only Company name will be displayed
$mail->Subject='CASH Trader | The Spirit Stone'; // This adds the subject title in the subject line field
// Create a connection to MySQL and the database:
$con = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection is active:
if(!$con) {
header('Location: alternate.php');
}
$result = mysqli_query($con, "SELECT fname, email FROM emails WHERE condition = 'condition'");
/* fetch associative array */
while ($row = $result->fetch_array()) {
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
$mail->AddAddress($user['email']);
$mail->Body="<!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>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>CASH Trader</title>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
</head>
<body yahoo bgcolor=\"#ccffff\" style=\"margin:0; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px;\">
<table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\">
<tr>
<td style=\"padding-top:20px; padding-right:0px; padding-bottom:30px; padding-left:0px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\">
<tr>
<td class=\"header\" align=\"center\" bgcolor=\"#333333\" style=\"padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<img src=\"http://www.girrawaagames.com/img/logo.jpg\" style=\"color:#FFFFFF\" alt=\"Cash Trader Logo\" style=\"display:block; max-width:100%; height:auto;\" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor=\"#ffffff\" style=\"padding-top:40px; padding-right:30px; padding-bottom:20px; padding-left:30px;\">
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">
<tr>
<td align=\"center\" style=\"color:#153643; font-family:Arial, Helvetica, sans-serif; font-size:24px;\">
<b>Hi " . $user['fname'] . "</b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>";
print_r($user['fname']);
print_r($user['email']);
if ($mail->send()) {
$updateCampaign = "UPDATE emails SET column = 'value' WHERE email = '" . mysqli_real_escape_string($row['email']) . "'";
$results = mysqli_query($con, $updateCampaign);
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
mysqli_free_result($result);
mysqli_close($con);
You need to concatenate the $useremail for it to have multiple emails.
$userEmail = '';
foreach($rows as $row) {
$userFname = $row["fname"];
$userEmail .= $row["email"] . ',';
}
It would probably be easier to pair these in an array..
foreach($rows as $row) {
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
Then you don't need the explode function later.
....
or better yet set it in the while loop, dont need foreach at all.
while($row = $result->fetch_array()){
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
Update:
<?php
// Script Error Reporting
//error_reporting(0);
// Require the form_functions to process the form
require('databaseConnect.php');
// Require the Email Class Functions
require("mailApp/class.phpmailer.php");
require("mailApp/class.smtp.php");
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive=true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->setFrom("No_Reply#girrawaagames.com", "Girrawaa Games"); // Valid email address from sender and Company name. Only Company name will be displayed
$mail->Subject='CASH Trader | The Spirit Stone'; // This adds the subject title in the subject line field
// Create a connection to MySQL and the database:
$con = mysqli_connect($hostname, $username, $password, $database);
// Check if the connection is active:
if(!$con) {
header('Location: alternate.php');
exit();
}
$result = mysqli_query($con, "SELECT fname, email FROM emails WHERE condition = 'condition'");
/* fetch associative array */
while ($row = $result->fetch_array()) {
$user['fname'][] = $row["fname"];
$user['email'][] = $row["email"];
}
foreach($user['email'] as $key => $email) {
$mail->AddAddress($email);
$mail->Body="<!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>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>CASH Trader</title>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
</head>
<body yahoo bgcolor=\"#ccffff\" style=\"margin:0; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px;\">
<table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\">
<tr>
<td style=\"padding-top:20px; padding-right:0px; padding-bottom:30px; padding-left:0px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\">
<tr>
<td class=\"header\" align=\"center\" bgcolor=\"#333333\" style=\"padding-top:10px; padding-right:10px; padding-bottom:10px; padding-left:10px; color:#153643; font-size:28px; font-weight:bold; font-family:Arial, Helvetica, sans-serif;\">
<img src=\"http://www.girrawaagames.com/img/logo.jpg\" style=\"color:#FFFFFF\" alt=\"Cash Trader Logo\" style=\"display:block; max-width:100%; height:auto;\" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor=\"#ffffff\" style=\"padding-top:40px; padding-right:30px; padding-bottom:20px; padding-left:30px;\">
<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">
<tr>
<td align=\"center\" style=\"color:#153643; font-family:Arial, Helvetica, sans-serif; font-size:24px;\">
<b>Hi " . $user['fname'][$key] . "</b>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>";
if ($mail->send()) {
$updateCampaign = "UPDATE emails SET column = 'value' WHERE email = '" . mysqli_real_escape_string($row['email']) . "'";
$results = mysqli_query($con, $updateCampaign);
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
mysqli_free_result($result);
mysqli_close($con);
}
You say you've looked everywhere... apart from code you already have! There is a mailing list example provided with PHPMailer that does exactly what you ask, correctly and efficiently.
In your code you're trying to send one message to 50 people, not 50 to 50, and it would also expose all addresses to all recipients, so this is generally a bad idea.
You've based your code on an obsolete example and are probably using an old version of PHPMailer, so get the latest.

Record won't update MySQL with PHP

I cannot for the life of me figure out why the below will not update the record. It gives me a success message but does not actually update the record. I have gone through tons off revisions and tried everything I can think of. Can anyone else see where the issue is?
<?php
$id = $_POST['id'];
$username = $_POST['username'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$company = $_POST['company'];
$rep1 = $_POST['rep1'];
$rep2 = $_POST['rep2'];
$rep3 = $_POST['rep3'];
$phone = $_POST['phone'];
$fax = $_POST['fax'];
$cell = $_POST['cell'];
$service = $_POST['service'];
$license = $_POST['license'];
$expdate = $_POST['expdate'];
$active = $_POST['active'];
$userlevel = $_POST['userlevel'];
$host="XXXXXXX"; // Host name
$username="XXXXXX"; // Mysql username
$password="XXXXXXX"; // Mysql password
$db_name="XXXXXXX"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");
// update data in mysql database
$sql="UPDATE $tbl_name SET id='".$id."', fname='".$fname."', lname='".$lname."', email='".$email."', company='".$company."', rep1='".$rep1."', rep2='".$rep2."', rep3='".$rep3."', phone='".$phone."', fax='".$fax."', cell='".$cell."', service='".$service."', license='".$license."', expdate='".$expdate."', active='".$active."', userlevel='".$userlevel."'".
"WHERE id = '".$id."'";
$result=mysqli_query($con,$sql);
// if successfully updated.
if($result){
$emailID = "info#domain.com";
$subject = "Registration notification from. $fname . through website";
$body = <<<EOD
<table cellspacing="0" cellpadding="1" border="1">
<tbody>
<tr>
<td style="padding: 5px 10px;" width="150">Name: </td>
<td style="padding: 5px 10px;">$fname $lname</td>
</tr>
<tr>
<td style="padding: 5px 10px;" width="150">Mobile: </td>
<td style="padding: 5px 10px;">$cell</td>
</tr>
<tr>
<td style="padding: 5px 10px;" width="150">Email: </td>
<td style="padding: 5px 10px;">$email</td>
</tr>
<tr>
<td style="padding: 5px 10px;" width="150">License Number: </td>
<td style="padding: 5px 10px;">$license</td>
</tr>
</tbody>
</table>
EOD;
$headers = "From: info#domain.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n";
mail($emailID, $subject, $body, $headers );
echo "<h4>Thank you for updating your account info. We will authorize your account and notify you once we have verified your license number and expiration.</h4>";
}
else {
echo "ERROR";
}
?>
Your last value doesn't have a whitespace after it, so the where keyword is "stuck" to it.
Just add a space before the where and you should be OK:
$sql="UPDATE $tbl_name SET id='".$id."', fname='".$fname."', lname='".$lname."', email='".$email."', company='".$company."', rep1='".$rep1."', rep2='".$rep2."', rep3='".$rep3."', phone='".$phone."', fax='".$fax."', cell='".$cell."', service='".$service."', license='".$license."', expdate='".$expdate."', active='".$active."', userlevel='".$userlevel."'".
" WHERE id = '".$id."'"; // Note the additional space here
Your problem is general: a mess of periods and extra quotes means you can't see litle things like the space you needed in the query. Also you don't have a mysql error generated on query fail, that would have helped.
Other problems: you're typing too much. Why make variables for each post value that have the same name as the key when you can just construct your query? Also you need to escape your values.
Here's my take:
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");
$id=mysql_real_escape_string($id);
foreach($_POST as $k=>$v){
//exclude id
if($k!='id'){
//escape values
$escaped_value= mysql_real_escape_string($v);
//set up array for update query
$query_parts[]="$k='$escaped_value'";
//create variables with the same name as the key
${$k}=$v;
}
}
$sql="UPDATE $tbl_name SET ".implode(",",$query_parts)." $WHERE id = '$id' ";
$result=mysqli_query($con,$sql) or die(mysql_error());

How to embed HTML with PHP array in e-mail message?

I am trying to send an email whith the order details after visitor submit the order. I am trying to embed my order array result in a html tag but it is not working. Help please
senmail.php
<?php
$to = "member#yahoo.com";
$from = "sales#thesite.com";
$headers = "From: $from";
$subject = "Custom computer Order Confirmation Nunber_ $orderid";
$message = "
<html>
<body>
<p> This doesn't render well</p>
<table style="margin-left:50px; text-align:left;">
<tr>
<th style="width:20%; border-bottom:solid 1px #000;">Item ID</th>
<th style="width:40%; border-bottom:solid 1px #000">Description</th>
<th style="width:15%; border-bottom:solid 1px #000">Quantity</th>
<th style="width:20%; border-bottom:solid 1px #000">Unit Price</th>
</tr>
<?php
foreach($_SESSION["cart_array"]as $item):
$item_id=$item['part_id'];
$sql = mysqli_query($con,"SELECT * FROM product_description
WHERE product_id='$item_id' LIMIT 1");
While($row=mysqli_fetch_array($sql)){
$product_name=$row["name"];
}
?>
<tr>
<td><?php echo $item['part_id'] ?></td>
<td><?php echo $product_name ?></td>
<td><?php echo $item['quantity'] ?></td>
<td><?php echo $item['price'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
";
$mailsent = mail($to, $subject, $message, $headers);
.........
?>
bored enough to fix it all for you:
<?php
$to = "member#yahoo.com";
$from = "sales#thesite.com";
$headers = "From: $from";
$subject = "Custom computer Order Confirmation Nunber_ $orderid";
$message = '
<html>
<body>
<p> This doesn\'t render well</p>
<table style="margin-left:50px; text-align:left;">
<tr>
<th style="width:20%; border-bottom:solid 1px #000;">Item ID</th>
<th style="width:40%; border-bottom:solid 1px #000">Description</th>
<th style="width:15%; border-bottom:solid 1px #000">Quantity</th>
<th style="width:20%; border-bottom:solid 1px #000">Unit Price</th>
</tr>';
foreach($_SESSION["cart_array"] as $item){
$item_id = $item['part_id'];
$sql = mysqli_query($con,"SELECT * FROM product_description
WHERE product_id='$item_id' LIMIT 1");
While ( $row = mysqli_fetch_array($sql) ){
$product_name = $row["name"];
}
$message .= '
<tr>
<td>'.$item['part_id'].'</td>
<td>'.$product_name.'</td>
<td>'.$item['quantity'].'</td>
<td>'.$item['price'].'</td>
</tr>';
}
$message .= ' </table>
</body>
</html>';
$mailsent = mail($to,$subject,$message,$headers);
//.........
?>
i only fixed the basics, this is still far from ideal
You cannot embed PHP code inside strings and magically have it execute.
The correct approach would be to store the message in a string and use a processing loop to add to it. Such a result would look like:
$msg = "Beginning of message\n";
foreach($_SESSION["cart_array"]as $item) {
$item_id=$item['part_id'];
$sql = mysqli_query($con,"SELECT * FROM product_description
WHERE product_id='$item_id' LIMIT 1");
while ($row = mysqli_fetch_array($sql)) {
$product_name = $row["name"];
$msg .= "<td>$product_name</td>";
// Other message parts go here
}
$msg .= "End of message\n";
Alternately, you can go a very terrible route and use something like eval, but because I discourage such behavior I will not be providing an example.
You're not escaping the quotes in $message. use ' or \" for html instead. Also you don't need the extra PHP tags in the middle of $message as you're still writing in PHP. Inside your foreach concatenate $message with .= and by the end it will be a string which you can submit with your email. I haven't tested it but I cleaned up your code and made the suggested changes below.
$message = "
<html>
<body>
<p> This doesn't render well</p>
<table style="margin-left:50px; text-align:left;">
<tr>
...
Should be
$message = "
<html>
<body>
<p> This doesn't render well</p>
<table style=\"margin-left:50px; text-align:left;\">
<tr>
...
Here you go
<?php
$to = "member#yahoo.com";
$from = "sales#thesite.com";
$headers = "From: $from";
$subject = "Custom computer Order Confirmation Nunber_ $orderid";
$message = "<html>
<body>
<p>This doesn't render well</p>
<table style=\"margin-left:50px; text-align:left;\">
<tr>
<th style=\"width:20%; border-bottom:solid 1px #000\">Item ID</th>
<th style=\"width:40%; border-bottom:solid 1px #000\">Description</th>
<th style=\"width:15%; border-bottom:solid 1px #000\">Quantity</th>
<th style=\"width:20%; border-bottom:solid 1px #000\">Unit Price</th>
</tr>";
foreach( $_SESSION["cart_array"] as $item )
{
$item_id = $item["part_id"];
$sql = mysqli_query( $con, "SELECT * FROM product_decsription WHERE product_id='".$item_id."' LIMIT 1;" );
if($row=mysqli_fetch_array($sql))
{
$message .= "
<tr><td>".$item['part_id']."</td>
<td>".$row['name']."</td>
<td>".$item['quantity']."</td>
<td>".$item['price']."</td></tr>";
}
}
$message .= "</table></body></html>";
$mailsent = mail( $to, $subject, $message, $headers );
?>
EDIT: the headers to use html need to be:
$headers = "From: ".$from."\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

Categories