I spent all Sunday trying to figure this out but, I am not sure how to word it right. It checks every hour via Cron job for new sales. Then takes the product number and receipt number. It uses the product number to check an information database and gather all that info from each row for the newly sold products. Then for each sold product, I need to add the receipt number on the end of the array and insert all that information into a 3rd database that saves all the sales.
My main problem is I merge them and it won't insert into the database. I had it working the first time but only grabbed the first row.
<?php
//find out current time and 1 hour ago
$current_time = strtotime("now");
$tenmin_ago = strtotime('-10 min');
$hour_ago = strtotime('-1 hour');
//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database ///////////////////
//////////////////////////////////////////////////////////////////
// connect to EMAP sales MySQL server
$server='localhost';
$user='user';
$password='pass';
$database='sales_data';
$con = mysqli_connect($server,$user,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: SALES " . mysqli_connect_error();
}
//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database ////////////////////
//////////////////////////////////////////////////////////////////
//EM connect to DLGuard-EM MySQL server
$em_server='localhost';
$em_user='user';
$em_password='pass';
$em_database='databaseEM';
$em_con = mysqli_connect($em_server,$em_user,$em_password,$em_database);
//EM Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: EM " . mysqli_connect_error();
}
//EM grab store name
$em_dlg_store = "EM";
$em_rows = array();
$em_request = "SELECT * FROM customers WHERE date BETWEEN $hour_ago AND {$current_time}";
$em_result = mysqli_query($em_con, $em_request) or die("ERROR NO SALES EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_rows[] = $em_row["receipt"];
}
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales ////////////////////
//////////////////////////////////////////////////////////////////
$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE dlgprod_num='{$em_prod_num}' AND dlg_store='{$em_dlg_store}'";
$emap_result = mysqli_query($con, $emap_request) or die("ERROR dlg prod num EM");
while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] = $emap_row;
$em_emap_rows = array_merge($em_rows, $emap_rows);
/*VALUES ('$emap_sku', '$emap_dlgprod_num', '$emap_book_title', '$emap_dlgprod_price', '$emap_author_name', '$emap_author_email', '$emap_publisher', '$emap_dlg_store', '$em_receipt');";*/
// 1
$em_add_sql = "INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam, dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt)
VALUES ('$em_emap_rows');";
if ($con->multi_query($em_add_sql) === TRUE) {
} else {
echo "Error: " . $em_add_sql . "<br>" . $con->error;
}
?>
xxxxxxxxxxxxxxxxxxxxxxxxx Update 2/27/17 xxxxxxxxxxxxxxxxxxxxxx
Here is an updated version and it grabs the information but it loses the array for receipt somewhere in the merge or string section. Also, it puts the order wrong. instead of UPC, product number, title, price, etc. then start the next line for the second sale it mixes them together like upc, UPC, product number, product number, title, title, price, price when there are two sales.
Here is the new error. I am so close to figuring this out thank you. I am going to make 4 scripts and have them alternating checking all 4 stores for sales every hour.
Warning: array_map(): Argument #2 should be an array in /home1/lotscav1/public_html/Sales/scripts/sales-notif.php on line 53
Warning: implode(): Invalid arguments passed in /home1/lotscav1/public_html/Sales/scripts/sales-notif.php on line 53
Error: INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam, dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt) VALUES ('('EM2200002','EM2200002','1','1','Island Girl','Island Girl','4.95','4.95','Marshall Gibson','Marshall Gibson','jasminerice1993#gmail.com','jasminerice1993#gmail.com','Dan Cuneo','Dan Cuneo','EM','EM'),(),');
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EM2200002','EM2200002','1','1','Island Girl','Island Girl','4.95','4.95','Marsha' at line 2
Array
Here is the updated code
<?php
//find out current time and 1 hour ago
$current_time = strtotime("now");
$hour_ago = strtotime('-24 hour');
//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database ///////////////////
//////////////////////////////////////////////////////////////////
// connect to EMAP sales MySQL server
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database ////////////////////
//////////////////////////////////////////////////////////////////
$mysqli_em = new mysqli("localhost", "username", "password", "database");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno . ") " . $mysqli_em->connect_error;
}
//EM grab store name
$em_dlg_store = "EM";
$em_rows = array();
$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago' AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_rows[] = $em_row["receipt"];
}
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales ////////////////////
//////////////////////////////////////////////////////////////////
$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE dlgprod_num='$em_prod_num' AND dlg_store='$em_dlg_store'";
$emap_result = mysqli_query($mysqli, $emap_request) or die("Error dlg prod num EM");
while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] = $emap_row;
$em_emap_rows = array_merge($emap_rows, $em_rows);
/*VALUES ('$emap_sku', '$emap_dlgprod_num', '$emap_book_title', '$emap_dlgprod_price', '$emap_author_name', '$emap_author_email', '$emap_publisher', '$emap_dlg_store', '$em_receipt');";*/
// 1
$string = "";
foreach ($em_emap_rows as $key => $innerArr) {
$result = implode( array_map('quoteItems', $innerArr), ",");
$string .= "(" . $result . ")";
if( $key != count($array) - 1 ){
$string .= ",";
}
}
function quoteItems($item){
return "'" . $item . "'";
}
//$em_rowss = implode(",", $em_rows); this turns the receipt array into a string
$em_add_sql = "INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam, dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt)
VALUES ('$string');";
if ($mysqli->multi_query($em_add_sql) === TRUE) {
} else {
echo "Error: " . $em_add_sql . "<br>" . $mysqli->error . "<br>" . $em_rows;
}
?>
I'll assume that top part of the code works. But from here there are several things to check:
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales ////////////////////
//////////////////////////////////////////////////////////////////
$emap_rows = array();
$emap_request = "SELECT * FROM all_products WHERE dlgprod_num='{$em_prod_num}' AND dlg_store='{$em_dlg_store}'";
$emap_result = mysqli_query($con, $emap_request) or die("ERROR dlg prod num EM");
while ($emap_row = mysqli_fetch_array($emap_result)) $emap_rows[] = $emap_row;
Basically you put all rows you got from query to $emap_rows array, so it look more like:
$emap_rows = array(
0 => array(
'sku' => 'value',
'dlgprod_num' => 'value',
'dlgprod_nam' => 'value',
...
),
1 => array(
'sku' => 'value2',
'dlgprod_num' => 'value2',
'dlgprod_nam' => 'value2',
...
),
)
Are you expecting only 1 result from a previous query?
I'll presume that you're expecting only 1 row for receipt, otherwise it will make no sense to me. I'll presume that you want to add $em_rows value (receipt) to each $emap_rows
// $em_emap_rows = array_merge($em_rows, $emap_rows);
Maybe you can try:
foreach( $emap_rows as $emap_row ) {
$v = array_values( $emap_row );
$v[] = $em_rows[0]; // because I expect only 1 result, added to array
$em_add_sql = "INSERT INTO all_author_sales ";
$em_add_sql .= " (sku, dlgprod_num, dlgprod_nam, dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt) ";
$em_add_sql .= " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";
$em_con->prepare( $em_add_sql );
$em_con->bind_param( 'sssssssss', $v[0], $v[1], $v[2], $v[3], $v[4], $v[5], $v[6], $v[7], $v[8] );
$em_con->execute();
}
All in all I recommend creating entire script from scratch, making it less vulnerable to injects etc. and more precise in terms of which data is used. Do not rely on getting only 1 result if you do not specify that in your query (using LIMIT, for example).
Do not rely on data order, but on its key. I used in the example above
$v[0] but it would be much better to use $emap_row['sku'].
Note: The code is not tested, it's just my attempt to understand the script and make some help.
Looks like this could all be done in a single query:
INSERT INTO all_author_sales (sku, dlgprod_num, dlgprod_nam,
dlgprod_price, author_name, author_email, publisher, dlg_store, dlgcustomer_receipt)
SELECT ap.sku, ap.dlgprod_num, ap.dlgprod_nam, ap.dlgprod_price,
ap.author_name, ap.author_email, ap.publisher, ap.dlg_store, c.receipt
FROM customers c
INNER JOIN all_products ap
ON c.prod_num = ap.dlgprod_num
AND c.date BETWEEN '{$hour_ago}' AND '{$current_time}'
AND dlg_store='{$em_dlg_store}'
A few pointers to note:
It can be seen from the query in question that receipt is a column in customers table which goes into the all_author_sales as dlgcustomer_receipt. However, for all ap.* columns in the SELECT part of the query above, please use the appropriate column names from all_products table as applicable if they aren't the same as written in the query.
Since you're using MySQLi, please consider changing your code to include Prepared Queries for the sake of simplicity and security.
You just insert array as string VALUES('$em_emap_rows'). That is the error.
Solution
To loop for the array and quote every element in every array and then implode arrays in the main array.
$string = "";
foreach ($em_emap_rows as $key => $innerArr) {
$result = implode( array_map('quoteItems', $innerArr), ",");
$string .= "(" . $result . ")";
if( $key != count($array) - 1 ){
$string .= ",";
}
}
function quoteItems($item){
return "'" . $item . "'";
}
Then use Values($string)
Thank you for all the help. I couldn't make work what you gave me for my unique situation. However, it inspired me towards my working solution along with a little help from an old friend. Here is the code that now works.
<?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');
//////////////////////////////////////////////////////////////////
/////////////////// Connect to Sales Database ///////////////////
//////////////////////////////////////////////////////////////////
$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}
//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database ////////////////////
//////////////////////////////////////////////////////////////////
$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}
//Grab store name
$dlg_store = "EM";
$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales ////////////////////
//////////////////////////////////////////////////////////////////
$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
$sku_s = $row_s["sku"];
$dlgprod_num_s = $row_s["dlgprod_num"];
$book_title_s = addslashes($row_s["book_title"]);
$dlgprod_price_s = $row_s["dlgprod_price"];
$author_name_s = addslashes($row_s["author_name"]);
$author_email_s = $row_s["author_email"];
$publisher_s = $row_s["publisher"];
$dlg_store_s = $row_s["dlg_store"];
$add_sql_s = "INSERT INTO all_author_sales SET
`sku`='$sku_s',
`dlgprod_num`='$dlgprod_num_s',
`dlgprod_nam`='$book_title_s',
`dlgprod_price`='$dlgprod_price_s',
`author_name`='$author_name_s',
`author_email`='$author_email_s',
`publisher`='$publisher_s',
`dlg_store`='$dlg_store_s',
`dlgcustomer_receipt`='$em_receipt' ";
//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin#website.com";
$to = array($author_email_s, $admin_email);
//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";
//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,<br />
I just wanted to send you a message and let you know that the book or
books below have just been purchased.<br /><br />
Store: $dlg_store_s<br />
Receipt: $em_receipt<br />
Sku Number: $sku_s<br /><br />
Book Title: $book_title_s<br />
Publisher: $publisher_s<br />
Product Number: $dlgprod_num_s<br />
Price: $dlgprod_price_s<br /><br />
Sincerely,<br />
$sig<br /><br />
To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";
if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
mail (implode(',', $to), $subject, $message, $headers);
} else {
echo "Error: " . $add_sql_s . "<br>" . $mysqli_s-
>error . "<br>" . $string;
}
}
}
?>
i have wrote a php script to send an emails.In this script it checks whether current date is equal with the emailfly_date and email is = o.if that satisfies email will sent to the user.this script is working for one user at a one time.that if database has five records that that matches current criteria it sends the email only to the last id.what is the reason for this?
id
250
251
252
253
it will send the email only to the ID 253.but not to the others.
Here is mycode
<?php
include_once 'dbconnect.php';
$query = "SELECT ID,email, emailfly_date, CURRENT_DATE AS nowtime FROM xxx WHERE reqnum = '' AND email_sent = '0'";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$regid = $row['ID'];
$activemail= $row['nowtime'];
/*echo $regid . '<br />';
echo $activemail. '<br />';*/
}
$query = mysql_query("SELECT ID, email, reqnum, emailfly_date, email_sent FROM xxx WHERE ID = '$regid' AND emailfly_date = '$activemail'");
$rowdata = mysql_fetch_array($query);
$ID = $rowdata['ID'];
$email = $rowdata['email'];
$reqnum = $rowdata['reqnum'];
$emailfly_date = $rowdata['emailfly_date'];
$email_sent = $rowdata['email_sent'];
if ($reqnum != '') {
/* echo "not sucess";*/
} elseif ($email_sent == '1') {
/* echo "email already sent";*/
} elseif ($email_sent == '1' && $reqnum != '') {
/* echo "no way to send";*/
}
elseif($email_sent == '0' && $reqnum == '' ){
$ulink = "http://xxx.eewfewt.net/tttt/yyyy.php?ID=$regid";
$to = $email;
$subject = 'hoo'; // Give the email a subject
$message = '
Thanks for Using Trial Version!
If You Wish to Continue with the Monthly Paid Package.
------------------------
Click Below
Site Renewal link: ' . $ulink . '
'.$emailfly_date.'
------------------------ ';
$headers .= 'From:werwerwer.aaa.net' . "\r\n";
$headers .= 'Bcc:ewrwerer.aaa.net' . "\r\n";
mail($to, $subject, $message, $headers);
$upadtequery = mysql_query("UPDATE xxx SET email_sent ='1' WHERE ID = '$regid'");
echo "sucess";
}
else{
echo "bye";
}
?>
From $query = mysql_query(.....bla...bla... to last else{
echo "bye";
} Put all this inside your while loop.
Also if you fetch data from same table try to use single query.
mysql_() is depreciated now. So try to use mysqli_()
include_once 'dbconnect.php';
$query = "SELECT ID,email, emailfly_date, CURRENT_DATE AS nowtime FROM xxx WHERE id in ('250','251','252','253') AND email_sent = '0'";
$result = mysql_query($query) or die(mysql_error());
while($rowdata = mysql_fetch_array($result))
{
$ID = $rowdata['ID'];
$email = $rowdata['email'];
$reqnum = $rowdata['reqnum'];
$emailfly_date = $rowdata['emailfly_date'];
$email_sent = $rowdata['email_sent'];
$ulink = "http://xxx.eewfewt.net/tttt/yyyy.php?ID=$regid";
$to = $email;
$subject = 'hoo'; // Give the email a subject
$message = '
Thanks for Using Trial Version!
If You Wish to Continue with the Monthly Paid Package.
------------------------
Click Below
Site Renewal link: ' . $ulink . '
'.$emailfly_date.'
------------------------ ';
$headers .= 'From:werwerwer.aaa.net' . "\r\n";
$headers .= 'Bcc:ewrwerer.aaa.net' . "\r\n";
mail($to, $subject, $message, $headers);
$upadtequery = mysql_query("UPDATE xxx SET email_sent ='1' WHERE ID = '$ID'");
echo "sucess";
}
I got this code and it's old and I know I need to convert it to PDO (still learning) but I need to get this working right now.
I am trying to send multiple emails out based on the query. So in this particular query I get two results. So I need to send out two different emails to the group. If the query had 4 results, then I would need to send 4. Right now it is only sending the first result. How can I get it to loop through and send multiple emails.
Here is the code:
<?
// connection string ......
$production = "SELECT value1 FROM parameters WHERE name = 'IS_PRODUCTION' ";
$query = "SELECT accounts.username, email_activate.email, accounts.user_id, accounts.alt_id FROM accounts INNER JOIN email_activate ON accounts.user_id = email_activate.user_id WHERE dt_welcome = '0000-00-00 00:00:00' AND dt_start <= DATE_SUB(NOW(), INTERVAL 3 DAY)";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$message = "Hello ".$row['username'].", <br/><br/>";
$message .= "You recently subscribed to <bblah blah blah</b> ";
$message .= '(http://), ' ;
$message .= "the official ";
$message .= "source of <br /><br /> ";
if ($production == 'Y' ) {
$subject = "How can we Assist!";
$to = "".$row['email']."";
$result2 = mysql_query("UPDATE email_activate SET dt_welcome = NOW() WHERE user_id = '".$row['user_id']."' ");
} else {
$subject = "[TEST] Offer You Assistance";
$to = 'email1#email.com' . ', ';
$to .= 'email2#email.com ' . ', ';
$to .= 'email3#email.com';
$result2 = mysql_query("UPDATE email_activate SET dt_welcome = NOW() WHERE user_id = '".$row['user_id']."' ");
}
$headers = "Content-Type: text/html; charset=utf-8\r\n";
$queryEmail = "SELECT alt_id FROM lookup_roles WHERE spec_tag = 'public_email'";
$result3 = mysql_query($queryEmail) or die(mysql_error());
while ($row12 = mysql_fetch_array($resul3t)) {
mail($to, $subject, $message, $headers, "-f ".$row12[alt_id]."");
}
}
?>
So I fixed it, the above code works just fine. I forgot to use a different $result variable ---> Changed it from $result to $result3, this way it doesn't blank out the previous result which is why I was only getting 1 email. I knew it was something simple, just couldn't see it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
For whatever reason, whenever I submit the form, it doesn't add the inputted data to the database. It was working before... Which I think is what's frustrating me the most. I came back to it a couple of hours later, and surprise! Not inserting new rows into the database. Perhaps there's a slight error I may have done subconsciously by accident? Nothing stands out to me, though. :(
refer.html: http://pastebin.com/d1xQUJLR
generator.php: http://pastebin.com/CE2UX8zs
main.js: http://pastebin.com/CSQh9DKs
Just fixed some bugs in your code ;)
<?php
include_once "access.php";
$ref_email = $_POST["tf_ref_email"];
$ref_username = $_POST["tf_ref_username"];
$ref_ign = $_POST["tf_ref_ign"];
$access = new Access();
$crux = $access->getCrux();
$anchor = $access->getAnchor();
$user = $access->getUser();
try {
$pdo = new PDO($anchor, $user, $crux);
$stq = "INSERT INTO referred_users
(ref_id, ref_email, ref_username, ref_ign, ref_awarded, new_email, new_awarded)
VALUES (:ref_id, :ref_email, :ref_username, :ref_ign, :ref_awarded, :new_email, :new_awarded)";
for($i = 0; $i < min(count($_POST["emails"]), 10); $i++) {
$ref_id = $_POST["ref_ids"][$i];
$new_email = $_POST["emails"][$i];
$new_ref_id = checkId($ref_id, $pdo);
$query = $pdo->prepare($stq);
$results = $query->execute(
array(
':ref_id' => $new_ref_id,
':ref_email' => $ref_email,
':ref_username' => $ref_username,
':ref_ign' => $ref_ign,
':ref_awarded' => '0',
':new_email' => $new_email,
':new_awarded' => '0'
)
);
$to = $new_email;
$subject = "Check out this AMAZING Minecraft RP Server!";
$message = "You have been invited to join " . $ref_ign . " in Arithia! Enter your Referral ID in the provided link to get a head start on your first character!" . "\n";
$message .= "Referral ID: " . $new_ref_id . "\n";
$message .= "Redeem Rewards: " . "http://www.graphicgoldfish.com/referral/referral.html" . "\n";
$message .= "By redeeming your referral, you will get:" . "\n";
$message .= "- 300 Credit Points" . "\n";
$message .= "- 50 Ducats" . "\n";
$message .= "- 25 Cooked Beef" . "\n";
$message .= "- Identification Tome" . "\n";
$message .= "We look forward to seeing you in Arithia! For more information, visit: http://www.arithia.com" . "\n";
$headers = "From: $ref_email";
mail($to, $subject, $message, $headers);
}
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
function checkId($id, $con) {
$stmt = $con->prepare("SELECT ref_id FROM referred_users WHERE ref_id = :ref_id");
$stmt->bindParam(':ref_id', $id);
$stmt->execute();
if($stmt->rowCount() > 0) {
$new_id = (string)rand(1000000, 9999999);
return checkId($new_id, $con);
}
return $id;
}
This question already has answers here:
PHP does not display error messages
(5 answers)
Closed 8 years ago.
I am trying to run this script but it throws 500 INTERNAL ERROR PROBLEM though the code does not throw any error.
The script throws an Internal Server 500 error, but when I remove the second $user mail, it works fine.I want to send a confirmation mail as well on successful submission and redirect to the thank you page.I hope I have coded correctly.please help
<?php
//output variables
$output="";
$host="databasehost.com"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="databasename"; // Database name
$tbl_name="tablename"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="property-value" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result1 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="firstname" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result2 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="lastname" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result3 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="from_email" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result4 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="houseflat-nos" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result5 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="street" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result6 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="towncity" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result7 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="postcode" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result8 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="telephone" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result9 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="outstanding-mortgage" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
//echo $row['ID'];
$output = $row['field_value'];
$percentage = 75;
$prelim = ($percentage / 100) * $output;
}
while ($row = mysql_fetch_assoc($result1)) {
//echo $row['ID'];
$output1 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result2)) {
//echo $row['ID'];
$output2 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result3)) {
//echo $row['ID'];
$output3 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result4)) {
//echo $row['ID'];
$output4 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result5)) {
//echo $row['ID'];
$output5 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result6)) {
//echo $row['ID'];
$output6 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result7)) {
//echo $row['ID'];
$output7 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result8)) {
//echo $row['ID'];
$output8 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result9)) {
//echo $row['ID'];
$output9 = $row['field_value'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result,$result1,$result2,$result3,$result4,$result5,$result6,$result7,$result8,$result9);
// References to the name values in your HTML form
$field_property1 = $_POST['typeofproperty'];
$field_property2 = $_POST['bedrooms'];
$field_property3 = $_POST['bathrooms'];
$field_property4 = $_POST['toilets'];
$field_property5 = $_POST['reception'];
$field_property6 = $_POST['garage'];
$field_property7 = $_POST['garden'];
$field_property8 = $_POST['generalCondition'];
$field_property9 = $_POST['builtYear'];
$field_property10 = $_POST['centralHeating'];
$field_property11 = $_POST['doubleGlazing'];
$field_property12 = $_POST['structure'];
$field_property13 = $_POST['association'];
$field_property14 = $_POST['inblock'];
$field_property15 = $_POST['freehold'];
$field_property16 = $_POST['yearsleft'];
$field_property17 = $_POST['why'];
$field_property18 = $_POST['when'];
$field_property19 = $_POST['other'];
$field_property20 = $_POST['how'];
$field_property21 = $_POST['howLong'];
$field_property22 = $_POST['workforproperty'];
$field_property23 = $_POST['uniquefeatures'];
$field_property24 = $_POST['anythingelse'];
$user = "$output3";
$usersubject = "Thank You";
$userheaders = "From: mailsentfrom#email.com\n";
$usermessage = "Thank You for your Enquiry. A member of staff will be in contact shortly to discuss your requirements.";
// Since some emails are unknown, I reccomend using a known email sender to avoid messages to go directly to the SPAM folder
$field_sender = ' senderemail#email.com';
// In which address would you like to recieve the messages? Would you like a custom Subject for each?
$mail_to = ' myemailid#email.com';
$subject = '[QUALIFIED LEAD] Enuiry ';
// This builds the message
$body_message = 'From: '.$output1."\n";
$body_message .= 'Phone: '.$output8."\n";
$body_message .= 'Email: '.$output3."\n\n";
$body_message .= 'Flat: '.$output4."\n";
$body_message .= 'Street: '.$output5."\n";
$body_message .= 'City: '.$output6."\n";
$body_message .= 'ZIP: '.$output7."\n\n";
$body_message .= 'Property Value: '.$output."\n\n";
$body_message .= 'Offer Value: '.$prelim."\n";
$body_message .= 'Outstanding Value: '.$output9."\n\n";
$body_message .= 'Type of Property: '.$field_property1."\n";
$body_message .= 'Number of Bedrooms: '.$field_property2."\n";
$body_message .= 'Number of Bathrooms: '.$field_property3."\n";
$body_message .= 'Number of Separate Toilets: '.$field_property4."\n";
$body_message .= 'Number of Reception Rooms: '.$field_property5."\n";
$body_message .= 'Garage: '.$field_property6."\n";
$body_message .= 'Garden: '.$field_property7."\n";
$body_message .= 'General Condition of Property: '.$field_property8."\n";
$body_message .= 'Property Built In: '.$field_property9."\n";
$body_message .= 'Central Heating: '.$field_property10."\n";
$body_message .= 'Double Glazing: '.$field_property11."\n";
$body_message .= 'Structure of Property: '.$field_property12."\n";
$body_message .= 'Ex-Council/Housing association: '.$field_property13."\n\n";
$body_message .= 'Property in a Block: '.$field_property14."\n";
$body_message .= 'Freehold/Leasehold: '.$field_property15."\n";
$body_message .= 'Years of Leashold Left: '.$field_property16."\n";
$body_message .= 'Reason for Quick Sale: '.$field_property17."\n\n";
$body_message .= 'How soon: '.$field_property18."\n\n";
$body_message .= 'Any Loans Secured on Property: '.$field_property19."\n\n";
$body_message .= 'How Much Loan Secured: '.$field_property20."\n\n";
$body_message .= 'Property Currently in Market: '.$field_property21."\n\n";
$body_message .= 'For How Long: '.$field_property22."\n\n";
$body_message .= 'Any Work Done: '.$field_property23."\n\n";
$body_message .= 'Any Unique Feature: '.$field_property24."\n\n";
$body_message .= 'Additional Details to Buyer: '.$field_property25."\n\n";
// Email headers 'From' a known email address to avoid being taken as SPAM and 'Reply-to' the one that filed in the form
$headers = 'From: '.$field_sender."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
// Status, builds whole email structure
mail($mail_to, $subject, $body_message, $headers);
mail($user,$usersubject,$usermessage,$userheaders);
if(mail($mail_to, $subject, $body_message, $headers)){
header("Location: http://websitename.com/thankyou-page/);
}else{
header("Location: http://websitename.com");
}
exit;
?>
<?php
// close connection
mysql_close();
?>
change $user = "$output3"; to $user = $output3;
500 Internal Server Error is shown if your php code has fatal errors but error displaying is switched off. You may try this to see the error itself instead of 500 error page:
In your php file:
ini_set('display_errors', 1);
You can also check Apache error logs, if you have access to them.
If you remove/comment out the second mail() call, it works? You do know that you can put multiple "to" addresses and use just one mail(), don't you?
$mail_to = ' myemailid#email.com, '.$user;
I'm not sure if the leading space is causing any harm (try removing it if nothing else works). Now, is $user a legitimate email address? Have you printed it out to check it?
Or, you can add a "cc: " email address in the header, if you'd rather send it to the person that way.
Thanks for all the brilliant response guys! ( Álvaro G. Vicario, freak, Bart Friederichs, Bart Friederichs and not to forget Hassan)
It finally is sorted. Please find the be working code below: (feel free to modify it if you like)
<?php
ini_set('display_errors', 1);
//output variables
$output="";
$host="databasehost.com"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="databasename"; // Database name
$tbl_name="tablename"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="property-value" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result1 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="firstname" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result2 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="lastname" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result3 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="from_email" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result4 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="houseflat-nos" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result5 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="street" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result6 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="towncity" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result7 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="postcode" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result8 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="telephone" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
$result9 = mysql_query('SELECT `field_value` FROM `tablename` WHERE `field_name`="outstanding-mortgage" ORDER BY `submit_time` DESC LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
//echo $row['ID'];
$output = $row['field_value'];
$percentage = 75;
$prelim = ($percentage / 100) * $output;
}
while ($row = mysql_fetch_assoc($result1)) {
//echo $row['ID'];
$output1 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result2)) {
//echo $row['ID'];
$output2 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result3)) {
//echo $row['ID'];
$output3 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result4)) {
//echo $row['ID'];
$output4 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result5)) {
//echo $row['ID'];
$output5 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result6)) {
//echo $row['ID'];
$output6 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result7)) {
//echo $row['ID'];
$output7 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result8)) {
//echo $row['ID'];
$output8 = $row['field_value'];
}
while ($row = mysql_fetch_assoc($result9)) {
//echo $row['ID'];
$output9 = $row['field_value'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result,$result1,$result2,$result3,$result4,$result5,$result6,$result7,$result8,$result9);
// References to the name values in your HTML form
$field_property1 = $_POST['typeofproperty'];
$field_property2 = $_POST['bedrooms'];
$field_property3 = $_POST['bathrooms'];
$field_property4 = $_POST['toilets'];
$field_property5 = $_POST['reception'];
$field_property6 = $_POST['garage'];
$field_property7 = $_POST['garden'];
$field_property8 = $_POST['generalCondition'];
$field_property9 = $_POST['builtYear'];
$field_property10 = $_POST['centralHeating'];
$field_property11 = $_POST['doubleGlazing'];
$field_property12 = $_POST['structure'];
$field_property13 = $_POST['association'];
$field_property14 = $_POST['inblock'];
$field_property15 = $_POST['freehold'];
$field_property16 = $_POST['yearsleft'];
$field_property17 = $_POST['why'];
$field_property18 = $_POST['when'];
$field_property19 = $_POST['other'];
$field_property20 = $_POST['how'];
$field_property21 = $_POST['howLong'];
$field_property22 = $_POST['workforproperty'];
$field_property23 = $_POST['uniquefeatures'];
$field_property24 = $_POST['anythingelse'];
$user = "$output3";
$usersubject = "Thank You";
$userheaders = "From: mailsentfrom#email.com\n";
$usermessage = "Thank You for your Enquiry. A member of staff will be in contact shortly to discuss your requirements.";
// Since some emails are unknown, I reccomend using a known email sender to avoid messages to go directly to the SPAM folder
$field_sender = ' senderemail#email.com';
// In which address would you like to recieve the messages? Would you like a custom Subject for each?
$mail_to = ' myemailid#email.com, '.$user;
$subject = '[QUALIFIED LEAD] Enuiry ';
// This builds the message
$body_message = 'From: '.$output1."\n";
$body_message .= 'Phone: '.$output8."\n";
$body_message .= 'Email: '.$output3."\n\n";
$body_message .= 'Flat: '.$output4."\n";
$body_message .= 'Street: '.$output5."\n";
$body_message .= 'City: '.$output6."\n";
$body_message .= 'ZIP: '.$output7."\n\n";
$body_message .= 'Property Value: '.$output."\n\n";
$body_message .= 'Offer Value: '.$prelim."\n";
$body_message .= 'Outstanding Value: '.$output9."\n\n";
$body_message .= 'Type of Property: '.$field_property1."\n";
$body_message .= 'Number of Bedrooms: '.$field_property2."\n";
$body_message .= 'Number of Bathrooms: '.$field_property3."\n";
$body_message .= 'Number of Separate Toilets: '.$field_property4."\n";
$body_message .= 'Number of Reception Rooms: '.$field_property5."\n";
$body_message .= 'Garage: '.$field_property6."\n";
$body_message .= 'Garden: '.$field_property7."\n";
$body_message .= 'General Condition of Property: '.$field_property8."\n";
$body_message .= 'Property Built In: '.$field_property9."\n";
$body_message .= 'Central Heating: '.$field_property10."\n";
$body_message .= 'Double Glazing: '.$field_property11."\n";
$body_message .= 'Structure of Property: '.$field_property12."\n";
$body_message .= 'Ex-Council/Housing association: '.$field_property13."\n\n";
$body_message .= 'Property in a Block: '.$field_property14."\n";
$body_message .= 'Freehold/Leasehold: '.$field_property15."\n";
$body_message .= 'Years of Leashold Left: '.$field_property16."\n";
$body_message .= 'Reason for Quick Sale: '.$field_property17."\n\n";
$body_message .= 'How soon: '.$field_property18."\n\n";
$body_message .= 'Any Loans Secured on Property: '.$field_property19."\n\n";
$body_message .= 'How Much Loan Secured: '.$field_property20."\n\n";
$body_message .= 'Property Currently in Market: '.$field_property21."\n\n";
$body_message .= 'For How Long: '.$field_property22."\n\n";
$body_message .= 'Any Work Done: '.$field_property23."\n\n";
$body_message .= 'Any Unique Feature: '.$field_property24."\n\n";
$body_message .= 'Additional Details to Buyer: '.$field_property25."\n\n";
// Email headers 'From' a known email address to avoid being taken as SPAM and 'Reply-to' the one that filed in the form
$headers = 'From: '.$field_sender."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
// Status, builds whole email structure
if(mail($mail_to, $subject, $body_message, $headers)){
header("Location: http://websitename.com/thankyou-page/");
}else{
header("Location: http://websitename.com");
}
exit;
?>
<?php
// close connection
mysql_close();
?>