Select and send mail from my database

2019-06-13 04:54发布

问题:

I'm trying to get the emails column from MySQL database table and then sending emails to them. Below is my PHP code:

private function sendEmailTech() {
$select = $this->pdo->prepare("SELECT email FROM tbl_tech_email");
try {
    $select->execute();
    $data = $select->fetch();
    foreach($data as $datum=>$email){
        if ($email == '') { 
            $rows.=$email.',';
        } else {
            return false;
        }
    $rows = str_replace(',--','',$rows);
    $to = explode(',', $rows); // to change to array
    mail($$rows, "My Info", "Hello, I just sent a mail to You");
    }
}
catch (PDOException $e) {            
    die($e->getMessage());
}

What is the correct way to select a column field from MySQL table and send emails to the recipients associated with that column?

回答1:

Try something like this:

<?php
    function sendEmailTech() {
        $select = $this->pdo->query("SELECT email FROM tbl_tech_email");
        $select = $select->fetchAll();
        if(count($select) > 0) {
            foreach($select AS $recipient) {
                mail($recipient["email"], "My Info", "Hello, I just sent a mail to You");
            }
        } else {
            echo "No user to send email";
            die();
        }
    }
    // sendEmailTech();
?>