1

I want to pass the result of a mysql query to a variable that intergrades the email of our database to Mailchimp! However i don't know how to pass the mysql result to a variable!

More precise the query is:

$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);

How can I pass the result of the query to $data email?

2
  • By the time you get to $data = ..., $row will be false Commented Sep 27, 2017 at 10:45
  • you'd have to do it within the loop, since the value of $row changes each time the loop iterates. What you're doing now makes no logical sense, because your use of $row is completely out of its intended context. Commented Sep 27, 2017 at 10:50

2 Answers 2

1

Try something like this:

<?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";   
}

It will send all the email to mailchimp during the loop. 1 by 1.

Or you can use a separate loop to add it in the 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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

In your loop set the result in your array data like this :

$data = [];

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

}

later

syncMailchimp($data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.