构建mysqli_fetch_assoc数组

时间:2013-07-29 10:01:33

标签: php arrays yii swiftmailer

请原谅我的'新手',这是我在PHP中的第一个项目。我相信这是一个非常简单的问题...希望对某些人有一些简单的观点!

我正在尝试从我的数据库中获取一个数组,运行Swift_Plugins_DecoratorPlugin并创建一系列个性化消息以进行假脱机。

问题是,该脚本使用静态数据数组,但是当我尝试从数据库中引入实时数据时,我迷失了。我不知道如何从数据库创建一个数组以适合正确的方式。

如果有人可以提供帮助,我将非常感激!

到目前为止我所拥有的:

<?php

    $dbc = mysqli_connect('localhost', 'root', '', 'apptwo');
    $query = "SELECT id, username, email FROM users WHERE status=1";
    $result = mysqli_query($dbc, $query);
      $users = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $users[$row['email']] = $row['email'];
        $users[$row['username']] = $row['username'];
        $users[$row['id']] = $row['id'];
    }

    // Create the replacements array
    $replacements = array();
    foreach ($users as $user) {
      $replacements[$user["id"]] = array (
        "{fullname}" => $user["username"],
        "{transactions}" => $user["email"]
      );
    }

    $spool = new Swift_FileSpool(__DIR__."/spool");
    // Setup the transport and mailer
    $transport = Swift_SpoolTransport::newInstance($spool);

    // Create an instance of the plugin and register it
    $plugin = new Swift_Plugins_DecoratorPlugin($replacements);
    $mailer = Swift_Mailer::newInstance($transport);
    $mailer->registerPlugin($plugin);

    // Create the message
    $message = Swift_Message::newInstance();
    $message->setSubject("This email is sent using Swift Mailer");
    $message->setBody("You {fullname}, are our best client ever thanks " .
        " to the {transactions} transactions you made with us.");
    $message->setFrom("mailout@exampleco.com", "exampleco");

    // Send the email
    foreach($users as $user) {
      $message->setTo($user["email"], $user["fullname"]);
      $result = $mailer->send($message);
    }
    echo "SPOOLED $result emails";
    ?>

使用数组中的静态数据的工作版本:

<?php

$users = array(
  array(
    "fullname" => "name",
    "operations" => 100,
    "email" => "name@name.com"
  ),
  array(
    "fullname" => "name2",
    "operations" => 50,
    "email" => "name2@name.com"
  )
);

// Create the replacements array
$replacements = array();
foreach ($users as $user) {
  $replacements[$user["email"]] = array (
    "{fullname}" => $user["fullname"],
    "{transactions}" => $user["operations"]
  );
}

$spool = new Swift_FileSpool(__DIR__."/spool");
// Setup the transport and mailer
$transport = Swift_SpoolTransport::newInstance($spool);

// Create an instance of the plugin and register it
$plugin = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer = Swift_Mailer::newInstance($transport);
$mailer->registerPlugin($plugin);

// Create the message
$message = Swift_Message::newInstance();
$message->setSubject("This email is sent using Swift Mailer");
$message->setBody("You {fullname}, are our best client ever thanks " .
    " to the {transactions} transactions you made with us.");
$message->setFrom("mailout@exampleco.com", "exampleco");

// Send the email
foreach($users as $user) {
  $message->setTo($user["email"], $user["fullname"]);
  $result = $mailer->send($message);
}
echo "SPOOLED $result emails";
?>

非常感谢你,简。


SOLUTION:

使用Yii PHP Framework。

你需要将Swiftmailer上传到本地目录,路径'class'指向我的config / main.php中的Swiftmailer.php

在protected / config / main.php ...

'components'=>array(
.....

'mailer' => array(
                'class' => 'application.modules.swiftmailer.SwiftMailer',

                // Using SMTP:
                'mailer' => 'smtp',
                // security is optional
                // 'ssl' for "SSL/TLS" or 'tls' for 'STARTTLS'
                'security' => '', 
                'host'=>'mail.example.com',
                'from'=>'mailout@example.com',
                'username'=>'mailout@example.com',
                'password'=>'pw',

                // Using sendmail:
                //'mailer'=>'sendmail',

                // Logging
                // logs brief messages about message success or failhure
                'logMailerActivity' => 'true', 
                // logs additional info from SwiftMailer about connection details 
                // must be used in conjunction with logMailerActivity == true
                // check the send() method for realtime logging to console if required
                'logMailerDebug' => 'true', 
),
),

decorator.php - 这会发送电子邮件并将它们发送到'spool'文件。

<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con){
    die('Could not connect: ' . mysql_error());
}

mysql_select_db('database', $con) or die(mysql_error()) ;

$sql = "SELECT * FROM tablename"; 
$result = mysql_query($sql, $con);
if( $result ){
while ($row = mysql_fetch_assoc($result)) {
    $user = array(
        'email' => $row['email'],
        'username' => $row['username'],
        'id' => $row['id']
    );
    $users[] = $user;
}
}
else{
  /* error! */
};


// Create the replacements array
$replacements = array();
foreach ($users as $user) {
  $replacements[$user["email"]] = array (
    "{username}" => $user["username"],
    "{transactions}" => $user["id"]
  );
}

$spool = new Swift_FileSpool(__DIR__."/spool");
// Setup the transport and mailer
$transport = Swift_SpoolTransport::newInstance($spool);

// Create an instance of the plugin and register it
$plugin = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer = Swift_Mailer::newInstance($transport);
$mailer->registerPlugin($plugin);

// Create the message
$message = Swift_Message::newInstance();
$message->setSubject("Subject text");
$message->setBody("<b>Dear {username}</b>,<br><br>Perhaps you would like to try xyz circle. " .
    " thank you for the {transactions} transactions you made with us.", 'text/html');
$message->setFrom("example@example.com", "example name");
$message->addPart("Plain text HTML Body You {username}, are our best client ever thanks " .
    " thank you for the {transactions} transactions you made with us.", 'text/plain');

// Send the email
foreach($users as $user) {
  $message->setTo($user["email"], $user["username"]);
  $result = $mailer->send($message);
}
echo "SPOOLED $result emails";
?>

spoolsend.php - 这会运行假脱机队列以发送邮件:

<?php
//create an instance of the spool object pointing to the right position in the filesystem
$spool = new Swift_FileSpool(__DIR__."/spool");

//create a new instance of Swift_SpoolTransport that accept an argument as Swift_FileSpool
$transport = Swift_SpoolTransport::newInstance($spool);

//now create an instance of the transport you usually use with swiftmailer
//to send real-time email
$realTransport = Swift_SmtpTransport::newInstance(
    "mail.example.com",
    "25"
)
    ->setUsername("example@example.com")
    ->setPassword("pw");

$spool = $transport->getSpool();
$spool->setMessageLimit(10);
$spool->setTimeLimit(100);
$sent = $spool->flushQueue($realTransport);

echo "SENT $sent emails";

?>

如果有任何人有任何问题,请告诉我,我也许可以提供帮助。

1 个答案:

答案 0 :(得分:1)

最好使用它:

while ($row = mysqli_fetch_assoc($result)) {
    $user = array(
        'email' => $row['email'],
        'username' => $row['username'],
        'id' => $row['id']
    );
    $users[] = $user;
}