Jump to content

PHP create csv, insert into db, send email with attachment to a bcc address


Recommended Posts

I'm trying to after submission

 

1. create a csv

2. insert record into db

3. send email that's created in form submission - $msg.

4. send email with attachment to only the email I specify (if possible)

if not attach it to the email that's created at submission. 

 

I've search and search and found different methods but doesn't work with my code.

I kept 3 lines at the top but can't get them to work ... either I don't get an email after submission or don't get an attachement. 

 

Can some one help?

<?php 

$random_hash = md5(date('r', time()));

$csvString = "..."; // your entire csv as a string
$attachment = chunk_split(base64_encode($csvString));

$to = "email@email.com";


if(isset($_POST['submit'])) 
{ 
  

// VALIDATION

  if(empty($_POST['firstName'])) 
  { 
   
   "First Name Required";
  } 
  
     
 if(empty($_POST['lastName'])) 
  { 
   
   "Last Name Required"; 
  
  }
  
  if(empty($error))  
  { 
   
	$to = "$to";
	$subject = 'The Form';
        $headers = "MIME-Version: 1.0 \r\n";
	$headers .= "Content-Type: text/html; \r\n" ;
	
   $msg .="<html>
	<head></head>
    <body>
    <table width='100%' cellspacing='0' border='0' cellpadding='0'>
    <tr><td>
    	<table width='100%' cellspacing='0' border='0' cellpadding='0'>
           <tr><td>This is the email sent.</td></tr>
        </table>
      </body>
    </html>";

  include('con.php');
	
	 $con = mysqli_connect($host,$user,$pass,$dbName);
	 if (!$con)
	  {
	  die('Could not connect: ' . mysqli_error($con));
	  }

      mysqli_select_db($con,"thetable");
	  
	 $firstName = mysqli_real_escape_string($con, $_POST['firstName']);
	$lastName = mysqli_real_escape_string($con, $_POST['lastName']);
						
	$sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'";
		
       $result = mysqli_query($con,$sql);
		 
	if(($result->num_rows)>= 1)
	{
	$theerror = "You exist"; 
	}
		
	else
	{
		  
	  $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'";
		   
		   $success = "Sent ... Insert it!!!"; 
		   
		   
	      if (!mysqli_query($con,$sql))
		  {
		  die('Error: ' . mysqli_error($con));
		  }
		   
		   $result = @mail($to, $subject, $msg, $headers); 
		}
		 
	   mysqli_close($con);

     
      { 
       
      } 
    } 
  } 
 
?> 
Edited by barkly

I tried this code and I'm receiving the emails without an attachment and the email show me the code instead of the actual email.

 

Anyone have any suggestions? 

<?php 

$to = "email@email.com";


if(isset($_POST['submit'])) 
{ 
  

// VALIDATION
  
 
  
  if(empty($_POST['firstName'])) 
  { 
   
   "First Name Required";
		
  } 
  
     
 if(empty($_POST['lastName'])) 
  { 
   
   "Last Name Required"; 
  
  }
  
    

  if(empty($error))  
  { 
   
	$to = "$to";
	$subject = 'The Form';
	
    $headers = "MIME-Version: 1.0 \r\n";
	$headers .= "Content-Type: text/html; \r\n" ;


    
	
	
   $msg .="<html>
	<head></head>
    <body>
    <table width='100%' cellspacing='0' border='0' cellpadding='0'>
    <tr><td>
    	<table width='100%' cellspacing='0' border='0' cellpadding='0'>
           <tr><td>This is the email sent.</td></tr>
        </table>
      </body>
    </html>";





     include('connection.php');
	
	 $con = mysqli_connect($host,$user,$pass,$dbName);
	 if (!$con)
	  {
	  die('Could not connect: ' . mysqli_error($con));
	  }

      mysqli_select_db($con,"thetable");
	  
	 
	$firstName = mysqli_real_escape_string($con, $_POST['firstName']);
	$lastName = mysqli_real_escape_string($con, $_POST['lastName']);
						
	$sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'";
	$result = mysqli_query($con,$sql);
		 
	if(($result->num_rows)>= 1)
	{
	$theerror = "You exist"; 
	}
		
	else
       {
$sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'";
		   
	$success = "Sent ... Insert it!!!"; 
		   
		   
	      if (!mysqli_query($con,$sql))
		  {
		  die('Error: ' . mysqli_error($con));
		  }
		   
		   	 //The Attachment

            $cr = "\n";
            $data = "Email" . ',' . "First Name" . ',' . "Last Name" . $cr;
            $data .= "$email" . ',' . "$firstName" . ',' . "$lastName" . $cr;
            $fp = fopen('diploma_apprenticeship_form_sub.csv','a');
            fwrite($fp,$data);
            fclose($fp);

            $attachments[] = Array(
               'data' => $data,
               'name' => 'diploma_apprenticeship_form_sub.csv',
               'type' => 'application/vnd.ms-excel'
            );


            //Generate a boundary string

            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";


            //Add the headers for a file attachment


            $headers = "MIME-Version: 1.0\n" .
                       "From: {$from}\n" .
                       "Content-Type: multipart/mixed;\n" .
                       " boundary=\"{$mime_boundary}\"";


            //Add a multipart boundary above the plain message


            $message = "This is a multi-part message in MIME format.\n\n" .
                      "--{$mime_boundary}\n" .
                      "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
                      "Content-Transfer-Encoding: 7bit\n\n" .
                      $text . "\n\n";


            //Add sttachments

            foreach($attachments as $attachment){
               $data = chunk_split(base64_encode($attachment['data']));
               $name = $attachment['name'];
               $type = $attachment['type'];

               $message .= "--{$mime_boundary}\n" .
                          "Content-Type: {$type};\n" .
                          " name=\"{$name}\"\n" .
                          "Content-Transfer-Encoding: base64\n\n" .
                          $data . "\n\n" ;
            }

            $message .= "--{$mime_boundary}--\n";
			
		   $result = @mail($to, $subject, $msg, $headers, $message); 
		}
		
		 
	   mysqli_close($con);

     
      { 
       
      } 
    } 
  } 
 
?> 
Edited by barkly

It's a scaled down version giving you what you need to help.  But since we have a smart-a not a problem.  Let's see how good you really are ginerjm, solve the issue.  Your little error script which I do use doesn't give me any errors.  So come on I challenge you.   Figure out why I recieve code emails ... meaning I see the code rather that the images etc.  What's your advanced solution? 

 

 SEE my comments.  And as for being a smart-a  - WHO post sham code and asks for help?

//  YOU ARE HASHING A DATE AND TIME ???
$random_hash = md5(date('r', time()));
$csvString = "..."; // your entire csv as a string
$attachment = chunk_split(base64_encode($csvString));
$to = "email@email.com";
if(isset($_POST['submit']))
{
 // VALIDATION
 if(empty($_POST['firstName']))
 { //  ERROR HERE
  "First Name Required";
 }
 if(empty($_POST['lastName']))
 { //  ERROR HERE
  "Last Name Required";
 }
 if(empty($error)) 
 {
  // WHY REDEFINING $TO HERE???
  $to = "$to";
  $subject = 'The Form';
  //  NEED A FROM ADDRESS IN HEADERS
  $headers = "MIME-Version: 1.0 \r\n";
  $headers .= "Content-Type: text/html; \r\n" ; 
  //  NEED TO START WITH = HERE NOT .=
  $msg .="<html>
  <head></head>
  <body>
  <table width='100%' cellspacing='0' border='0' cellpadding='0'>
  <tr><td>
  <table width='100%' cellspacing='0' border='0' cellpadding='0'>
  <tr><td>This is the email sent.</td></tr>
  </table>
  </body>
  </html>";
  include('con.php');
  $con = mysqli_connect($host,$user,$pass,$dbName);
  if (!$con)
  {
   die('Could not connect: ' . mysqli_error($con));
  }
  // ARE YOU SURE DB AND TABLE ARE BOTH NAMED 'THETABLE'????
  // AND WHY SELECT IT WHEN YOU ARE DOING IT IN CONNECT ???
  mysqli_select_db($con,"thetable");
  $firstName = mysqli_real_escape_string($con, $_POST['firstName']);
  $lastName = mysqli_real_escape_string($con, $_POST['lastName']);
  //  DON'T NEED {} AROUND VARS HERE
  //  YOU SAY THAT IF YOU GET A HIT THAT THE PERSON EXISTS. 
  //  WHAT IF YOU LOOK FOR JOHN SMITH AND FIND JOHN DOE?
  $sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'";
  $result = mysqli_query($con,$sql);
  if(($result->num_rows)>= 1)
  {
   $theerror = "You exist";
  }
  else
  {
   //  NO NO NO...  DON'T INSERT THE UNSANITIZED INPUTS HERE!!!!!
   $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'";
   $success = "Sent ... Insert it!!!";
   if (!mysqli_query($con,$sql))
   {
    die('Error: ' . mysqli_error($con));
   }
   // WHY OH WHY DO PEOPLE SUPPRESS ERRORS HERE????? REMOVE THE @ CHAR
   $result = @mail($to, $subject, $msg, $headers);
  }
  mysqli_close($con);
  //   WHAT IS THIS FOR???
  {
  }
 }
}
Edited by ginerjm

So where is your solution man?  Again posting nothing acting like you're a pro.   Show us how good you really are.   Don't worry about what I'm looking for before inserting that's not the question.... I have my reasons and that's why it's posted.  Also READ look at the second code example or are you BLIND?  Show us how to insert a CSV in an email with the code provided.  Come on since you're a great coder. ... .  Do you really think I would name a table thetable???? Dude stick to the issue of attaching a csv and stop wasting everyones time.  I'm sure there's many people wondering how to do this and you're asking if I name the table thetable. 

 

Is there anyone who could help answer the questions with code example on how to attach a csv after form submission?  

Edited by barkly

You orig post said you didn't get an email or you didn't get the mail with the att.

 

As I posted a few mins ago (where did it go?) I had success with this code (and some modifications to make it error free) and it sends me an email.  As for the attatchment I don't see that code here so I'm not about to fix it.

 

Curb your attitude at the door please.  And don't post pseudo-code or "code" that you haven't actually run.  It makes us all irritable here.

 

Have a good life.

Attitude?? Are you kidding me?  I believe you need to look at yourself and read you comments buddy.  

 

My second post has the attachment code.... learn to read please.  It says, "I'm receiving the emails without an attachment and the email shows me the code instead of the actual email."....   Look for the  comment in the code  //The Attachment   look for it in the second post...   You have some issues ..  go search for help on google.  We are not ALL pros that's why we ask for help here ... if you can't take someone asking for help, maybe go somewhere else where all the other pros go to and see how good you really are. 

 

You are nuts dude. 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.