-1

I am working on a project where I send the information being stored in the session variable $_SESSION['favourites'].

I made use of the print_r function print_r($_SESSION, true) and it did work with the output being as follows

Array
(
    [favourites] => Array
        (
            [0] => Array
                (
 [item_id] => 3
                )

            [1] => Array
                (
                    [item_id] => 11
                )

        )

)

Instead I implemented a foreach with a while loop to display the contents and store them in a variable $email_message. The problem with the code is that since $email_message is a variable it is being overwritten and echoed in a while loop.

My main objective is to send all the information in the session variable over email.

This is the phpmailer code including the foreach and while loop mentioned above.

<?php
        use PHPMailer\PHPMailer\PHPMailer;
        foreach($_SESSION["favourites"] as $key => $value)
        {  
            $id = $value['item_id'];

            $sql= "SELECT * FROM menu WHERE id = '$id'";
            $result=mysqli_query($conn, $sql);
            $resultcheck=mysqli_num_rows($result);
            while($row=mysqli_fetch_assoc($result))
            {  
                $email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
            }
            echo $email_message;
        }
                   
        if(isset($_POST['fullname']) && isset($_POST['email']))
        {
            $name = $_POST['fullname'];
            $email = $_POST['email'];
            $subject = 'My favourite\'s list as of '. date("Y/m/d");

            //Calling the PHPMailer 'functions' 
            require_once "vendor\phpmailer\phpmailer\src\PHPMailer.php";
            require_once "vendor\phpmailer\phpmailer\src\SMTP.php";
            require_once "vendor\phpmailer\phpmailer\src\Exception.php";

            $mail = new PHPMailer();

            //SMTP Settings
            //$mail -> SMTPDebug = 3;
            $mail -> isSMTP();
            $mail -> Host = "smtp.gmail.com";
            $mail -> SMTPAuth = true;
            $mail -> Username = "cis1045sem2a2021@gmail.com";
            $mail -> Password = 'universityofmalta';
            $mail -> Port = 587; 
            $mail -> SMTPSecure = "tls"; 

            //Email Settings
            $mail -> isHTML(true);
            $mail -> setFrom($email, $name);
            $mail -> addAddress("cis1045sem2a2021@gmail.com");
            $mail -> Subject = $subject;
            $mail -> Body = $email_message;

            if ($mail->send()) {
                echo "Email is sent!";
            } else {
                echo "Something is wrong: <br><br>" . $mail->ErrorInfo;
            }
        }
       
?>

This is the favourites page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>El Tabata</title>

    <link rel="shortcut icon" type="image/x-icon" href="./assets/images/mexican-mascot.png"/>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <link rel="stylesheet" href="./assets/CSS/styles.css">
    <link rel="stylesheet" href="./assets/CSS/responsive.css">
</head>

<body>

<?php

    include 'header.php';
    include_once 'dbHandler.php';
    

    if(isset($_SESSION))
    {
        session_destroy();
    }
    session_start();

?>
<!-- THE REMOVAL FROM FAVOURITES -->
<?php
    if(isset($_GET["action"]))
    {
        if($_GET["action"] == "delete")
        {
            foreach($_SESSION["favourites"] as $keys => $values)
            {
                if($values["item_id"] == $_GET["id"])
                {
                    unset($_SESSION["favourites"][$keys]);
                    echo 'Item has been removed successfully';
                    echo '<script>window.location="favourites.php"</script>';
                }
            }
        }
    }

    if(!empty($_SESSION['favourites']))
    {
?>

        <section class="container">
    
            <ul id="contact_form" class="food-cards"> 
            <!-- DISPLAYING THE ITEMS IN THE SESSION VARIABLE THROUGH DATABASE -->
<?php
                    foreach($_SESSION["favourites"] as $key => $value)
                    {  
                        $id = $value['item_id'];

                        $sql= "SELECT * FROM menu WHERE id = '$id'";
                        $result=mysqli_query($conn, $sql);
                        $resultcheck=mysqli_num_rows($result);

                        while($row=mysqli_fetch_assoc($result))
                        {
?>
                            <li class="card-info">
                                <div class="food-card">
                                    <div class="food-pic">
                                        <img src="./assets/images/english-breakfast.png" alt="">
                                    </div>
                                    <div class="food-cont">
                                        <h2 class="food-title">
                                            <?php echo $row["name"]; ?>
                                        </h2>
                                        <div class="price-fav-btn">
                                            <div class="price"> 
                                                <?php echo "€".$row["price"]; ?>
                                            </div>

                                            <input type="hidden" name="hidden_id" value="<?php echo $row["id"]; ?>" />
                                            <a style="color: white;" href="favourites.php?action=delete&id=<?php echo $id; ?>">Remove from favorits</a>
                                        </div>
                                    </div>
                                </div>
                            </li>

<?php
                        }
                    }
?>
            </ul>
            
            <div class="form-fav">
                    <form id="contact_form" method="POST">
                        <input type="text" name="fullname" placeholder="Full Name" required>
                        <input type="text" name="email" placeholder="Email" required> 
                        <!-- <input type="text" name="body" placeholder="Start typing your message" required>   -->
                        <button class="frm-btn" type="submit" name="submit" value="Submit">Submit</button>
                    </form>
            </div>

         </section>

<?php
        echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
        require 'emailfunction.php';
    }   
    
    else
    {
?>
            <section>
                <div class="container">
                    <h4> Please add an item to your favourite's list. </h4>
                    <img src="./assets/images/sad-taco.jpg" alt="sad-taco">
                </div>
            </section>
<?php 
    } //end of main if-else statement
?> 

<?php include 'footer.php' ?>       
<script src="main.js"></script>

</body>
</html>

This is the html preview

Html Preview

This is the email preview where it is only sending 1 item only.

Function is sending 1 item only

This is what I am trying to achieve where it sends every item in 1 email.

What I am trying to achieve

Anthony Mifsud
  • 112
  • 1
  • 10
  • 2
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 28 '21 at 14:11
  • 1
    So instead of overwriting, append to the variable? I'm sure you're familiar with string concatenation. Or you could build an array of lines you want to use for your e-mail content and just implode them with a new line. – El_Vanja May 28 '21 at 14:11
  • Please share more details - what have you tried to resolve the problem? And how is sending an email related to CSS? – Nico Haase May 28 '21 at 14:32
  • I did what @El_Vanja said and what combinu answer below. I basically appended to $email-message by using the ' .= ' and intialised $email-message before the foreach loop. – Anthony Mifsud May 28 '21 at 14:33

2 Answers2

1

Change this:

 $email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';

to this:

 $email_message .= ($row['id']). ($row['name']). ($row['price']).'<br>';

That's what El_Vanja was saying.

SaintFrag
  • 127
  • 1
  • 13
1

If i understood correctly the problem is here:

 $email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';

This way you always replacing the value in $email_message

Instead of that you should concatenate the message as follows

First declare $email_message = ''; before the loop

And in the loop write:

$email_message .= ($row['id']). ($row['name']). ($row['price']).'<br>';

or

$email_message .= ($row['id']). ($row['name']). ($row['price']).PHP_EOL;

And by the way the help is coming from Malta too ;)

Combinu
  • 882
  • 2
  • 10
  • 31