PHP将mysql结果传递给变量

时间:2017-09-27 10:42:23

标签: php mysql mysqli

我想将mysql查询的结果传递给将数据库的电子邮件整合到Mailchimp的变量!但是,我不知道如何将mysql结果传递给变量!

查询更精确:

$sql = "SELECT email, DATE_FORMAT(users.reg, '%Y-%m-%d') FROM users  
WHERE DATE(reg) = CURDATE()";
$result = $conn->query($sql);

if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc())
    {
        echo " " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}


$data = [
    'email'     => $row["email"],
    'status'    => 'subscribed'
];

syncMailchimp($data);

如何将查询结果传递给$data电子邮件?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

<?php

$sql = "SELECT email, DATE_FORMAT(users.reg, '%Y-%m-%d') FROM users  
WHERE DATE(reg) = CURDATE()";
$result = $conn->query($sql);

$data = [];
if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc())
    {
        $data = [
            'email'     => $row["email"],
            'status'    => 'subscribed'
        ];
        syncMailchimp($data);
    }

} 
else 
{
    echo "0 results";   
}

它会在循环期间将所有email发送到mailchimp。 1比1。

或者您可以使用单独的循环将其添加到syncMailchimp

<?php

$sql = "SELECT email, DATE_FORMAT(users.reg, '%Y-%m-%d') FROM users  
WHERE DATE(reg) = CURDATE()";
$result = $conn->query($sql);

$emails = [];
if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc())
    {
        $emails[] = [
            'email'     => $row["email"],
            'status'    => 'subscribed'
        ];
    }

} 
else 
{
    echo "0 results";   
}


foreach($emails as $email){
    syncMailchimp($email);
}

答案 1 :(得分:0)

在循环中将结果设置为数组数据,如下所示:

$data = [];

while($row = $result->fetch_assoc())
{
$data[] = [
'email'     => $row["email"],
'status'    => 'subscribed'
];

}

syncMailchimp($data);