0

I have a PHP-script that import data from a MySQL database and send send an email to said persons with the help of a while loop. Everything works fine except that I can't use variable values in the email body (instead the name of the variable is printed out). Example, if I write ".$first_name." I want the body of the email to say "Johan" if that's the name of the entry in the database.

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

        // About database
        $user       = "user";  
        $password   = "password";  
        $host       = "host";  
        $dbase  = "dbase";  
        $table  = "table";

        // Connection to database  
        $dbc= mysqli_connect($host,$user,$password, $dbase)  
        or die("Unable to select database"); 

        // Retrieve emails from database
        $country    = $_POST['country'];

        $query= "SELECT email, firstname FROM $table WHERE country = '$country'"; 
        $result= mysqli_query ($dbc, $query)  
        or die ('Error querying database.'); 

        // Send the email
        while ($row = mysqli_fetch_array($result)) { 

            // Write $first_name for recipients name
            $first_name = $row['firstname']; 
            $last_name  = $row['lastname']; 
            $email      = $row['email']; 

            // About the email
            $from       = 'info@email.com';
            $subject    = $_POST['heading']; 
            $body       = $_POST['message']; 
            $speed      = $_POST['speed'];

            mail($email, $subject, $body, 'From:' . $from); 
            echo 'Email sent to: ' . $email. '<br>'; 

            // Delay for speed regulation
            sleep(3600/$speed);
        } 

    }

mysqli_close($dbc); 

I guess the problem must be either here:

$query= "SELECT email, firstname FROM $table WHERE country = '$country'"; 
$result= mysqli_query ($dbc, $query)  
or die ('Error querying database.'); 

Or here:

$first_name = $row['firstname']; 
$last_name = $row['lastname']; 
$email     = $row['email']; 
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Lavonen
  • 606
  • 1
  • 10
  • 21
  • 5
    `$body = $_POST['message'];` You're populating the body with the content of a POSTed value, not with anything that you're fetching from the db. – Patrick Q Dec 15 '17 at 20:10
  • 2
    If you're using mysqli functions, you may as well [bind your parameters](http://php.net/manual/en/mysqli-stmt.bind-param.php) for security purposes instead of dumping variables haphazardly in the query – cteski Dec 15 '17 at 20:10
  • Yes, it's kind of the point. I send the email from a website where I write the message in an input field (body). I want to be able to write $first_name in the body and get "John" as a result. Is that possible? – Lavonen Dec 15 '17 at 20:17
  • Your message body is - fortunately - not evaluated as php so if you want to replace texts there, you need to do that manually using for example `str_replace()`. – jeroen Dec 15 '17 at 20:18
  • 2
    I'd suggest creating a defined list of replaceable tokens such as `{{firstName}}`, `{{lastName}}`, etc and replace them with the appropriate values using the function mentioned above by jeroen. – Patrick Q Dec 15 '17 at 20:19
  • Since the body of that email is coming from a posted value, you can either do what @PatrickQ has suggested (recommended) or concatenate the database value to content like: `$body = $first_name. " ".$_POST["message"];` – iVoidWarranties Dec 15 '17 at 20:24
  • Sounds good, I will check it out right away! – Lavonen Dec 15 '17 at 20:24
  • Possible duplicate of [Replacing Placeholder Variables in a String](https://stackoverflow.com/questions/15773349/replacing-placeholder-variables-in-a-string) – Patrick Q Dec 15 '17 at 20:24
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Dec 15 '17 at 20:37
  • Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Dec 15 '17 at 20:37

2 Answers2

2

Assuming $_POST['message'] has content that looks something like...

Dear $first_name,
Greetings, I am a prince from...

PHP is not going to replace the variable. That is just something it does in inline strings (when using double quotes).

print("Test... $first_name");

There are a dozen different ways you could handle this... for example you could :

$body = str_replace('$first_name', $first_name, $body);

Note the use of SINGLE quotes. This is to prevent PHP from using the value of $first_name, and instead using the literal string '$first_name'.

DragonYen
  • 958
  • 9
  • 22
0

In your line $query= "SELECT email, firstname FROM $table WHERE country = '$country'"; you have to add lastname too.

layekams
  • 49
  • 6