Sending one email for a receipt instead of two? - php

I added a cart function to this website, before It would only send one email after purchase because there was only one item at a time being purchased, now that I have added the cart function it needs to send one email instead of multiple emails.
This is the code I am using for processing the items purchased.
EDIT: Updated code
$item = array();
$size = array();
$color = array();
$price = array();
$querys = "SELECT * FROM ".$_SESSION["username"];
$ress = mysqli_query($connection, $querys);
if(mysqli_num_rows($ress) > 0){
while($rows = $ress->fetch_assoc()){
$bid = $rows["itemid"];
$description = $_POST["description"];
$bitem = $rows["itemname"];
$bsize = $rows["size"];
$bcolor = $rows["color"];
$bprice = $rows["price"];
$bcategory = $rows["category"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$company = $_POST["company"];
$address = $_POST["address"];
$suite = $_POST["suite"];
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
$country = $_POST["country"];
$saddress = $_POST["saddress"];
$ssuite = $_POST["ssuite"];
$scity = $_POST["scity"];
$sstate = $_POST["state"];
$szip = $_POST["szip"];
$scountry = $_POST["scountry"];
$phone = $_POST["phone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$website = $_POST["website"];
$creditcard = $_POST["creditcard"];
$exdate = $_POST["experationdate"];
$cvv = $_POST["cvv"];
$create_date = date( 'Y-m-d H:i:s' );
$str_bitem = str_replace("'", "''", $bitem);
array_push($item, $bitem);
array_push($size, $bsize);
array_push($color, $bcolor);
array_push($price, $bprice);
$gw = new gwapi();
$gw->setLogin("demo", "password");
$gw->setBilling($firstname, $lastname, $company, $address, $suite, $city, $state, $zip, $country, $phone, $fax, $email, $website);
$gw->setShipping($firstname, $lastname, $company, $saddress, $ssuite, $scity, $sstate, $szip, $scountry, $email);
$gw->setOrder($bid, $description, 0, 0, 0, $_SERVER["REMOTE_ADDR"]);
$gw->doSale($bprice, $creditcard, $exdate, $cvv);
if($gw->responses['response'] == 1){
$firstname = $_SESSION["firstname"];
$lastname = $_SESSION["lastname"];
$query = "INSERT INTO orders (item_name, item_id, item_size, item_color, payer_email, first_name, last_name, address_name, address_city, address_state, address_zip, amount, country, create_date, shipped)
VALUES ('$str_bitem', '$bid', '$bsize', '$bcolor', '$email', '$firstname', '$lastname', '$saddress', '$scity', '$sstate', '$szip', '$bprice', '$scountry', '$create_date', 0)";
if(mysqli_query($db, $query)){
if($bsize=="N/A" && $bcolor=="N/A"){
define('DB_SERVER1', 'localhost');
define('DB_USERNAME1', 'grampmkn_gramsandpops');
define('DB_PASSWORD1', 'Grams123');
define('DB_DATABASE1', 'grampmkn_shop');
$db1 = mysqli_connect(DB_SERVER1,DB_USERNAME1,DB_PASSWORD1,DB_DATABASE1);
$sqlquery = "UPDATE `".$bcategory."` SET sold='1' WHERE id='$bid'";
if(mysqli_query($db1, $sqlquery)){
echo "Worked!";
}else{
echo "Error! : ";
echo mysqli_error($db1);
}
}else{
echo $bsize;
echo ":::::::";
echo $bcolor;
$conn = mysqli_connect('localhost', 'grampmkn_gramsandpops', 'Grams123', 'grampmkn_shop_quantity');
$query = "SELECT quantity FROM `".$bitem."` WHERE size='$bsize' AND color='$bcolor'";
$result = $conn->query ($query) or die($conn->error);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$q = --$row["quantity"];
$query = "UPDATE `$bitem` SET quantity='$q' WHERE size='$bsize' AND color='$bcolor'";
if(mysqli_query($conn, $query)){
}else{
echo "TESTHING1";
echo mysqli_error($conn);
}
}
}else{
$query = "SELECT quantity FROM `".$bitem."` WHERE size='$bsize'";
$result = $conn->query ($query) or die($db->error);
while($row = $result->fetch_assoc()){
$q = --$row["quantity"];
$query = "UPDATE `$bitem` SET quantity='$q' WHERE size='$bsize'";
if(mysqli_query($conn, $query)){
}else{
echo "TESTING";
echo mysqli_error($conn);
}
}
}
}
}else{
echo mysqli_error($db);
echo " ::::: ";
echo mysqli_error($connection);
}
$masked = str_pad(substr($creditcard, -4), strlen($creditcard), '*', STR_PAD_LEFT);
$transid = $gw->responses['transactionid'];
$username = $_SESSION["username"];
$query = "DELETE FROM $username WHERE itemid='$bid'";
if(mysqli_query($connection, $query)){
echo "Worked";
}else{
echo "Error! ";
echo mysqli_error($connection);
}
$query = "show tables;";
$tres = $connection->query($query) or die($connection->error);
if($tres->num_rows > 0){
while($trow = $tres->fetch_assoc()){
$table = $trow["Tables_in_grampmkn_cart"];
$sql = "DELETE FROM `".$table."` WHERE category='$table' AND itemid='$bid'";
if(mysqli_query($connection, $sql)){
echo "Deleted items from others carts!";
}else{
echo "There were no similar items in others carts!";
echo $table." : ";
echo $tcategory." : ";
echo mysqli_error($connection);
}
}
}
}else{
?>
<div class="alert alert-warning">
<strong>Error!</strong> Your card was declined!
</div>
<?php
}
}
$itemlist = implode(', ', $item);
$sizelist = implode(', ', $size);
$colorlist = implode(', ', $color);
$pricelist = implode(', ', $price);
if(!empty($bcolor)){
$to = $email;
$subject = "Purchase Confirmation";
$txt = "Thank you for your purchase of <br> ".$sizelist." ".$itemlist." - ".$colorlist."<br>Price: ".$pricelist."<br>Transaction ID: ".$transid."<br>CC: ".$masked."<br> <img src='https://gramsandpops.com/images/Logo.png'>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: info#gramsandpops.com' . "\r\n" .
'Reply-To: info#gramsandpops.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if(mail($to,$subject,$txt,$headers)){
}
}else{
$to = $email;
$subject = "Purchase Confirmation";
$txt = "Thank you for your purchase of <br> ".$sizelist." ".$itemlist."<br>Price: ".$pricelist."<br>Transaction ID: ".$transid."<br>CC: ".$masked."<br> <img src='https://gramsandpops.com/images/Logo.png'>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: info#gramsandpops.com' . "\r\n" .
'Reply-To: info#gramsandpops.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if(mail($to,$subject,$txt,$headers)){
}
}
$to = "gramsandpopsblueridge#gmail.com";
$subject = "Purchase Order";
$txt = "Item: ".$itemlist."\n Size: ".$sizelist."\n Color: ".$colorlist."\n Price: ".$pricelist."\n Address: ".$saddress.
" ".$scity.", ".$sstate." ".$szip."\n Name: ".$firstname." ".$lastname."\n CC: ".$masked;
$headers = "From: admin#gramsandpops.com" . "\r\n" .
"CC: admin#gramsandpops.com";
if(mail($to,$subject,$txt,$headers)){
}
?>
<div class="alert alert-success">
<strong>Success!</strong> Your transaction was successfully processed! An email confirmation will be sent shortly.
</div>
<?php
}else{
echo mysqli_error($connection);
}

Related

Send learners reminder email and admin

Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?
below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}

how to get the following url to show 1 week instead of just 1

I have the following code and for my last variable called $duration, it should say 1 week but I think it is only showing 1. Should the following code work? I am trying to send the following link to an activation page but on the activation page, instead of showing 1 week for the variable $duration, it is only showing as 1. I don't think this is correct I thought that it should have worked..
<?php
include_once __DIR__.'/header2.php';
if(!isset($_SESSION['u_uid'])) {
echo "<meta http-equiv='refresh' content='0;url=index.php?level1promo_competitions_winner=notlogin'>";
exit();
} else {
if($_SESSION['u_permission'] == 0) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?level1promo_competitions_winner=nopermission'>";
exit();
} else {
if(!isset($_POST['submit'])) {
echo "<meta http-equiv='refresh' content='0;url=header2.php?level1promo_competitions_winner=error'>";
exit();
} else {
include_once __DIR__.'/includes/dbh.php';
$levelpromo_competitions_winner_form = strip_tags($_POST['levelpromo_competitions_winner_form']);
if ($levelpromo_competitions_winner_form == $levelpromo_competitions_winner_form) {
$limit = 1;
$sql = "SELECT * FROM level1promo_participants WHERE entry_id = ? ORDER BY RAND() LIMIT ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "si", $levelpromo_competitions_winner_form, $limit);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck < 1) {
echo '<div class="nolevel1promo_competitions_winner">There are no Level 1 Promo Competition\'s Winner yet for that entry id</div>';
exit();
} else {
$row = mysqli_fetch_assoc($result);
$useruid = $row['user_uid'];
$email = $row['user_email'];
$duration = $row['duration'];
$sql2 = "INSERT INTO level1promo_winner (entry_id, duration, user_uid, user_email) VALUES (?,?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ssss", $levelpromo_competitions_winner_form, $duration, $useruid, $email);
mysqli_stmt_execute($stmt);
$subscriptionplan = 'Level 1';
$level1promocode = 'qqewreqreqwsdfdfdafcbvcQERFGHFGHGFHRETERTDF!##$%^^()';
$level1promocode = str_shuffle($level1promocode);
$level1promocode = substr($level1promocode, 0, 10);
$sql3 = "UPDATE memberships
SET subscriptionplan = ?, token = ?
WHERE user_uid = ? AND user_email = ? AND subscriptionplan IS NULL
;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql3)) {
echo "SQL statement failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ssss", $subscriptionplan, $level1promocode, $_SESSION['u_uid'], $_SESSION['u_email']);
mysqli_stmt_execute($stmt);
$stmt = mysqli_stmt_init($conn);
$sql4 = "SELECT * FROM level1promo_winner WHERE entry_id = ?;";
if (!mysqli_stmt_prepare($stmt, $sql4)) {
echo "SQL statement failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $levelpromo_competitions_winner_form);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$to = $_SESSION['u_email'];
//sender
$from = 'pianocourse101#hotmail.com';
$fromName = 'PianoCourse101';
//email subject
$subject = 'Congratulation Level 1 Promo Winner!';
//attachment file path
$file = "codexworld.pdf";
//email body content
$htmlContent = "<h1>Congratulation Level 1 Promo Winner!</h1>
<p>Dear ".$_SESSION['u_first']." ".$_SESSION['u_last'].", <br />Thank you for applying for the Level 1 Promo Competition with the following entry_id: ".$row['entry_id']." with PianoCourse101! You are receiving this e-mail because you or someone else claiming to be you has applied for the Level 1 Promo Competition. \n\n You must activate your Level 1 Promo Code by clicking on the link below: \n\n Click here to activate your Level 1 Promo Code.\n\nAlternatively, you can use the following token to manually activate your Level 3 Yearly Membership Plan by clicking on the 'Activate Membership\s Section:' \n\nToken:.$level1promocode;
</p>";
//header for sender info
$headers = "From: $fromName"." <".$from.">";
//boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
//multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
//preparing attachment
if(!empty($file) > 0){
if(is_file($file)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($file,"rb");
$data = #fread($fp,filesize($file));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .
"Content-Description: ".basename($file)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $from;
//send email
$mail = mail($to, $subject, $message, $headers, $returnpath);
//email sending status
echo $mail?"<h1>Mail sent.</h1>":"<h1>Mail sending failed.</h1>";
echo $duration;
When I echo $duration but in my mail function, it is only showing up as 1..

Newsletter works with mysql_connect but not with PDO

I want to script a Newsletter.
With mysql_connect the newsletter does work; Email received and my echo string with listed emails also work.
If I want to translate it to PDO, any email is sent and no string to see, also i do not get any error message. (German strings in script)
<?php
mysql_connect('localhost', 'name', 'pw')
or die ("Verbindung fehlgeschlagen");
mysql_select_db('***')
or die ("Datenbank nicht gefunden");
$betreff = 'Newsletter';
$nachricht = 'Sehr geehrte/geehrter ##anrede## ##vorname## ##nachname##,' . "\n\n" .
'der neue Newsletter ist da.';
$header = 'FROM: newsletter#test.abc' . "\r\n" .
'Replay-To: anfrage#test.abc';
$sql = "SELECT * FROM newsletter";
$erg = mysql_query($sql);
$sqlemail = "SELECT email FROM newsletter";
$result = mysql_query($sqlemail);
while($row = mysql_fetch_object($result)) {
$email = $row->email;
foreach ($row as $email) {
mail($email, $betreff, $nachricht, $header);
echo "Email versendet an $email <br />";
}
}
?>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=***', 'name', 'pw');
$betreff = 'Newsletter';
$nachricht = 'Sehr geehrte/geehrter ##anrede## ##vorname## ##nachname##,' . "\n\n" .
'der neue Newsletter ist da.';
$header = 'FROM: newsletter#test.abc' . "\r\n" .
'Replay-To: anfrage#test.abc';
$sql = "SELECT * FROM newsletter";
$erg = mysql_query($sql);
foreach ($pdo->query($sql) as $row) {
$email = $row['email'];
mail($email, $betreff, $nachricht, $header);
echo "Email versendet an $email <br />";
}
?>
In the pdo side, you need to fetch the query as well. Do this:
$pdo->query($sql)->fetchAll()

How to update in php using array after sending an email?

I have this link and then processed by this script:
<html>
<head>
</head>
<?php
/*//Disable error reporting
error_reporting(0);
*/
//Report runtime errors
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
//<script>location.replace("http://www.mntr.xxx.com/update.php");</script>
//Report all errors
error_reporting(E_ALL);
//end of error reporting
if(isset($_POST['submit']) && $_POST['submit'] == 'Send') {
//var_dump($_POST['users']);
$size= sizeof($_POST['users']);
$i = 0;
$message = NULL;
// $message = null;
for($i=0; $i<$size; $i++){
$userId = $_REQUEST['users'][$i];
$message .= mailContent($userId);
}
$to = $_POST['email'];
$subject = 'This is a test';
$headers = 'From: xxx#live.com.ph' . "\r\n" .
'Reply-To: xxx#live.com.ph' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-Type: text/html; charset=ISO-8859-1\r\n';
mail($to, $subject, $message, $headers);
}
function mailContent($userId) {
$con=mysqli_connect("localhost","xxx","xxx","xxx");
$stmt = "SELECT * from CV where idvisa = '$userId'";
$result = mysqli_query($con, $stmt);
$row=mysqli_fetch_array($result);
$fName = $row['fName'];
$lName = $row['lName'];
$visaNumber = $row['visanumber'];
$idNumber = $row['idnumber'];
$statusApp = $row['statusapp'];
$accntVisaPhotoPath = $row['accntVisaPhotoPath'];
$passportPath = $row['passportPath'];
$message = "Your Username: YOUR EMAIL (small caps) PASSWD: 1234
<table>
<tr>
<td>Name</td><td>$fName $lName</td>
</tr>
<tr>
<td>CVs</td><td>Click Here</td>
</tr>
<tr>
<td>Visa Number</td><td>$visaNumber</td>
</tr>
<tr>
<td>ID Number</td><td>$idNumber</td>
</tr>
<tr>
<td>Application Status</td><td>$statusApp</td>
</tr>
<tr>
<td>Visa Copy</td><td><a href='http://mntr.xxx.com/".$accntVisaPhotoPath."'>Click to Download</a></td>
</tr>
<tr>
<td>Passport Copy</td><td><a href='http://mntr.xxx.com/".$passportPath."'>Click to Download</a></td>
</tr>
</table>";
// OTHER LOGICS GO HERE
return $message;
}
//Additional var
//Time
date_default_timezone_set('Asia/Manila');
//End Time
$email = $_POST['email'];
$subdate = date("Y-m-d");
$subdate2 = date("Y-m-d");
if (empty($subdate)) {
$sql="UPDATE CV SET subdateEmail='$email',subdate='$subdate WHERE idvisa='$userId'";
} else {
$sql="UPDATE CV SET subdateEmail2='$email',subdate2='$subdate2' WHERE idvisa='$userId'";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<center>You have sent CV(s) </b><br/><br/><br/><br/>YOU MAY NOW CLOSE THIS WINDOW</center>";
?>
It is working but I want to update 4 columns out of the selected users (in this case, idvisa) AFTER email. Right now, it doesn't update. I am thinking on the array that has been SELECTED.
Any idea?
Use this
error_reporting(E_ALL);
$con=mysqli_connect("localhost","xxx","xxx","xxx");
if(#mail($to, $subject, $message, $headers))
{
ate_default_timezone_set('Asia/Manila');
//End Time
$email = $_POST['email'];
$subdate = date("Y-m-d");
$subdate2 = date("Y-m-d");
if (empty($subdate)) {
$sql="UPDATE CV SET subdateEmail='$email',subdate='$subdate WHERE idvisa='$userId'";
} else {
$sql="UPDATE CV SET subdateEmail2='$email',subdate2='$subdate2' WHERE idvisa='$userId'";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<center>You have sent CV(s) </b><br/><br/><br/><br/>YOU MAY NOW CLOSE THIS WINDOW</center>";
}else{
echo "Mail Not Sent";
}

MySQL/PHP will not insert into database

I've been trying to add an email confirmation system to my website when people sign up and create an account but it will not add the key and the user id in the database. The other problem I'm running across is I'm trying to send a confirmation email but the email does not send. It echo's "message sent successfully" but when I check the email I put in, it is not received. Thanks in advance for your help! And yes, I am aware that mysql is prone to sql injection, but I would like to figure this out with mysql.
Here is my code:
EDIT: I replaced $insert_confirm with $hin and I renamed the table confirm to email_confirmation to maybe get rid of reserved words but I'm still getting an error
<?php
require_once '../scripts2/app_config.php';
require_once '../scripts2/database_connection.php';
$upload_dir = HOST_WWW_ROOT . "/uploads/profile_pics/";
$image_fieldname = "user_pic";
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$name = $first_name . " " . $last_name;
$username = trim($_REQUEST['username']);
$password = trim($_REQUEST['password']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
if(isset($_POST['submit1'])) {
if($_POST['picture'] == 'picture1') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
} else if($_POST['picture'] == 'picture2') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387547040-auto_pic_grey2.png";
} else if($_POST['picture'] == 'picture3') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
} else {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
}
}
$bgcolor = "#FF0000";
$check_email = "SELECT `email`" .
" FROM users" .
" WHERE `email` = '$email'";
$query_email = mysql_query($check_email);
$check_username = "SELECT `username`" .
" FROM users" .
" WHERE `username` = '$username'";
$query_username = mysql_query($check_username);
if(mysql_num_rows($query_email)>0 || mysql_num_rows($query_username)>0 ) {
if(mysql_num_rows($query_email)>0) {
$email_msg = "This email is already taken: {$email}";
header("Location:signup2.php?error_message={$email_msg}");
} else if(mysql_num_rows($query_username)>0) {
$username_msg = "This username is already taken: {$username}";
header("Location:signup2.php?error_message={$username_msg}");
} else {
$msg = "This email and username is already taken: {$email} , {$username}";
header("Location:signup2.php?error_message={$msg}");
}
} else {
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, name, username, " .
"password, email, " .
"bio, " .
"user_pic_path, bgcolor) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($name),
mysql_real_escape_string($username),
mysql_real_escape_string(crypt($password, $username)),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($radio_value),
mysql_real_escape_string($bgcolor));
//insert the user into the database
$insert_user = mysql_query($insert_sql);
$private_user_id = mysql_insert_id();
function generateRandomString($length = 20) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$private_user_key = generateRandomString();
$hin = sprintf("INSERT INTO email_confirmation " .
"(user_id, key) " .
"VALUES (%d, '%s');",
mysql_real_escape_string($private_user_id),
mysql_real_escape_string($private_user_key));
//insert the user into the database
mysql_query($hin);
echo mysql_error();
$name = mysql_real_escape_string($_POST['name']);
$create_user_table = mysql_query("CREATE TABLE `".$email."` ( friend_id INT, friend_status INT)");
if($insert_user && $create_user_table) {
// Email the new user the confirmation key
$to = $email;
$subject = 'Welcome!';
$message = "
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<p>Please click the following link to confirm your email:</p>
<p>Confirm Email</p>
</body>
</html>
";
// 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";
// Additional headers
$headers .= 'From: Admin <email#email.com>' . "\r\n";
// Mail it
$retval = mail($to, $subject, $message, $headers);
if( $retval == true )
{
echo "Message sent successfully...";
echo "\n" . $to . "\n" . $message . "\n" . "\n" . $subject;
}
else
{
echo "Message could not be sent...";
}
}
//Redirect this user to the page that displays user information
// $msg = "Please check your email to confirm your email address";
// header("Location: newuser_signinA.php?error_message={$msg}");
// exit();
}
?>

Categories