0

I have admin dashboard. When user submit html form, All data is displayed in the admin panel.

index.php

<?php
$sql = "SELECT * FROM orders";
    if($result = mysqli_query($link, $sql)){
        if(mysqli_num_rows($result) > 0){
            echo "<div class='table-responsive pt-3'>";
            echo "<table class='table table-striped project-orders-table'>";
            echo "<thead>";
            echo "<tr>";
                echo "<th class='ml-5'>ID</th>";
                echo "<th>Client</th>";
                echo "<th>Email</th>";
                echo "<th>Address</th>";
                echo "<th>ZIP</th>";
                echo "<th>City</th>";
                echo "<th>Product</th>";
                echo "</tr>";
            echo "</thead>";
            echo "<tbody>";
        while($row = mysqli_fetch_array($result)){
            echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . $row['name'] . "</td>";
            echo "<td>" . $row['email'] . "</td>";
            echo "<td>" . $row['address'] . "</td>";
            echo "<td>" . $row['zip'] . "</td>";
            echo "<td>" . $row['city'] . "</td>";
            echo "<td><strong>" . $row['product'] . "</strong></td>";
            echo "<td>";
echo '<div class="d-flex align-items-center">
<a href="orders/createInvoice.php?id='. $row['id'] .'"><button type="button" class="btn btn-success btn-sm btn-icon-text">Invoice<i class="typcn typcn-document-add btn-icon-append"></i></button></a>
</div><br>';

echo '<div class="d-flex align-items-center">
<a href="orders/DeleteOrder.php?id='. $row['id'] .'"><button type="button" class="btn btn-danger btn-sm btn-icon-text">Delete<i class="typcn typcn-delete-outline btn-icon-append"></i></button></a>
</div>';
            echo "</td>";
            echo "</tr>";
            }
            echo "</tbody>";                         
            echo "</table>";

            mysqli_free_result($result);
            } else{
            echo '<div class="alert alert-danger"><em>No orders! :(</em></div>';
            }
            } else{
            echo "Oops! Something went wrong. Please try again later.";
            }

            mysqli_close($link);
?>

When i press Invoice button, i get redirected to: orders/createInvoice.php?id=1

createInvoice.php

require "sendInvoice.php";
session_start();

if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: Auth/Auth.php");
    exit;
}

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'martasme_noliktava');
define('DB_PASSWORD', 'O4Dhmi8D!');
define('DB_NAME', 'martasme_noliktava');
 
try{
    $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}

if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){

    $sql = "SELECT * FROM test WHERE id = :id";
    
    if($stmt = $pdo->prepare($sql)){
        $stmt->bindParam(":id", $param_id);

        $param_id = trim($_GET["id"]);

        if($stmt->execute()){
            if($stmt->rowCount() == 1){
                $row = $stmt->fetch(PDO::FETCH_ASSOC);

                $name = $row["name"];
                $email = $row["email"];
                $product = $row["product"];
            }
        }
    }

    unset($stmt);

    unset($pdo);
} else {
    header("location: success.php");
    exit();
}

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        
        <div class="form-group">
            <label>Client:</label>
            <input type="text" name="name" class="form-control" value="<?php echo $row["name"]; ?>" readonly>
        </div>
        
        <div class="form-group">
            <label>Email:</label>
            <input type="text" name="email" class="form-control" value="<?php echo $row["email"]; ?>" readonly>
        </div>

        <div class="form-group">
            <label>Order:</label><br/>
            <input type="text" name="product" class="form-control" value="<?php echo $row["product"]; ?>" readonly>
        </div>
        
        <div class="form-group">
            <label>Comment:</label>
            <input type="text" name="message" class="form-control" placeholder="Message">
        </div>
            
        <input type="submit" name="submit" class="btn btn-primary" value="Send">
            
</form>

Then, when i click submit, This code works: sendInvoice.php

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require '../../../vendor/PHPMailer/src/Exception.php';
require '../../../vendor/PHPMailer/src/PHPMailer.php';
require '../../../vendor/PHPMailer/src/SMTP.php';

require '../../../vendor/autoload.php';

$msg = '';
//Don't run this unless we're handling a form submission
if (array_key_exists('email', $_POST)) {
    date_default_timezone_set('Etc/UTC');

    //Create a new PHPMailer instance
    $mail = new PHPMailer();
    $mail->isSendmail();
    $mail->isSMTP();

    $mail->SMTPDebug = off;
    
    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';
    
    $mail->Port = 465;
    
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    
    //Username to use for SMTP authentication - use full email address for gmail
    $mail->Username = 'myGmail';
    
    //Password to use for SMTP authentication
    $mail->Password = 'myGmailAppPassword';

    //Use a fixed address in your own domain as the from address
    //**DO NOT** use the submitter's address here as it will be forgery
    //and will cause your messages to fail SPF checks
    $mail->setFrom('invoices@optical.eu', 'Invoices Department');
    //Choose who the message should be sent to
    //You don't have to use a <select> like in this example, you can simply use a fixed address
    //the important thing is *not* to trust an email address submitted from the form directly,
    //as an attacker can substitute their own and try to use your form to send spam
    $addresses = [
        'sales' => 'sales@optical.eu',
        'support' => 'support@optical.eu',
        'accounts' => 'account@optical.eu',
    ];
    //Validate address selection before trying to use it
    if (array_key_exists('dept', $_POST) && array_key_exists($_POST['dept'], $addresses)) {
        $mail->addAddress($addresses[$_POST['dept']]);
    } else {
        //Fall back to a fixed address if dept selection is invalid or missing
        $mail->addAddress($_POST['email'], 'Optical');
    }
    //Put the submitter's address in a reply-to header
    //This will fail if the address provided is invalid,
    //in which case we should ignore the whole request
    if ($mail->addReplyTo('orders@optical.eu')) {
        $mail->Subject = 'Your order at Optical';
        //Keep it simple - don't use HTML
        $mail->isHTML(false);
        //Build a simple message body
        $mail->Body = 
<<<EOT
    Name: {$_POST['name']}
    Email: {$_POST['email']}
    Product: {$_POST['product']}
    
    Pay by card: {$_POST['link']}
    Message: {$_POST['message']}
    
    
    NOTE: This is an automatically generated email, you will not be able to reply to this!
    If you have any questions about the order, write to us: orders@optical.eu
EOT;
        //Send the message, check for errors
        if (!$mail->send()) {
            
            $msg = 'Sorry, something went wrong. Please try again later.';
        } else {
            $msg = 'Message sent! Thanks for contacting us.';
        }
    } else {
        $msg = 'Invalid email address, message ignored.';
    }
}
?>

The email is sent, it's working. I would like to know how I can attach a pdf invoice to an e-mail with the product, e-mail, name and comment.

  • https://stackoverflow.com/questions/35997961/file-attachment-with-phpmailer refer to this – be MrZulf Aug 16 '22 at 14:51
  • 1
    Ouch... `SELECT *` without limit... that WILL break in the future, I promise ;) – Honk der Hase Aug 16 '22 at 14:53
  • 2
    There's a lot of background information and code here, but it seems like your actual question is just "how do I attach a file to an e-mail"? – IMSoP Aug 16 '22 at 15:48
  • I think it might be two parts: How to create a PDF from HTML, and how to attach that PDF to an email. – Chris Haas Aug 16 '22 at 16:24
  • 1
    I also recommend you learn how to use composer properly; If you use it correctly, you should effectively never need to write another include/require statement again. You can delete that 'isSendmail()` line; you don't need that. Short answer: generate the PDF, save it somewhere, and then attach it to your message with `addAttachment`. – Synchro Aug 16 '22 at 16:24
  • Yes, i need pdf, but only for the id I have selected. I currently have two records in a database table (2 records). If I choose ID 2, the pdf is sent to the e-mail address of the person with ID 2 – FurnitureStore Aug 16 '22 at 16:45
  • Where are you selecting the ID? You mean the GET parameter? It seems the code should already do what you are saying...it's unclear what specific problem you're having. There's a lot of code here...what debugging have you done? – ADyson Aug 16 '22 at 18:35
  • Lets say i choose user 1 with id 1. I can see his name, email, address and etc. Now i want to send him an invoice to email. With SELECT statement I get his data from the database and now the question is how to get it - that I can send him an email + attach a pdf invoice with the user data. I can create the invoice manually, but I think there is an option to do it automatically. – FurnitureStore Aug 16 '22 at 18:48
  • So actually you're asking how to automatically generate a pdf using php? There are libraries you can use, have you done any initial research? P.s. 90% of the code you've posted in your question is irrelevant to the issue, I think – ADyson Aug 16 '22 at 19:50

0 Answers0