我试图将mysqli转换为PDO:
`$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){
$to = $row['email'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name,\n$text";
mail($to, $subject, $msg, 'From:' . $from);
echo 'Email sent to: ' . $to . '<br />';
}
mysqli_close($dbc);
通过阅读其他问题,我尝试了这个:
$sql = "SELECT * FROM email_list";
while ($row = fetch(PDO::FETCH_BOTH)){
$to = $row['email'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name,\n$text";
mail($to, $subject, $msg, 'From:' . $from);
echo 'Email sent to: ' . $to . '<br />';
}
$conn->exec($sql);
$conn = null;
但是我收到了这个错误: 解析错误:语法错误,意外&#39; {&#39;在第36行的C:\ xampp \ htdocs \ sendemail.php中。
更新:
<?php
$from = 'elmer@makemeelvis.com';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$servername = "localhost";
$username = "davide";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=elvis_store", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully<br>";
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// $dbc = mysqli_connect('data.makemeelvis.com', 'elmer', 'theking', 'elvis_store')
// or die('Error connecting to MySQL server.');
// $sql = "SELECT * FROM email_list";
// while ($row = fetch(PDO::FETCH_BOTH))
// {
// $to = $row['email'];
// $first_name = $row['first_name'];
// $last_name = $row['last_name'];
// $msg = "Dear $first_name $last_name,\n$text";
// mail($to, $subject, $msg, 'From:' . $from);
// echo 'Email sent to: ' . $to . '<br />';
//
// }
$query = $conn->prepare("SELECT * FROM email_list");
$query->execute();
while($row = $conn->fetch(PDO::FETCH_BOTH)){
$to = $row['email'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name,\n$text";
mail($to, $subject, $msg, 'From:' . $from);
echo 'Email sent to: ' . $to . '<br />';
}
$conn->exec($sql);
$conn = null;
?>
成功连接
注意:未定义的变量:第47行的C:\ xampp \ htdocs \ study \ ch03 \ final \ makemeelvis \ sendemail.php中的dbc
致命错误:在null中调用成员函数prepare() 第47行的C:\ xampp \ htdocs \ study \ ch03 \ final \ makemeelvis \ sendemail.php
更新2:
我还没有出现这个错误,但是现在html页面继续加载...没有给出任何错误但也没有消息作为&#34;已连接&#34;或类似的......
我做错了什么?
感谢
答案 0 :(得分:0)
这应该为你做到!
$query = $conn->prepare("SELECT * FROM email_list");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$to = $row['email'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name,\n$text";
mail($to, $subject, $msg, 'From:' . $from);
echo 'Email sent to: ' . $to . '<br />';
}
编辑:
戴夫,使用上面编辑的代码,你应该没问题。我将解释您为何会收到错误。
我原来的回复是使用变量$ dbc,而你的PDO数据库连接字符串......
$conn = new PDO("mysql:host=$servername;dbname=elvis_store", $username, $password);
使用变量$ conn作为PDO处理程序。
希望这是有道理的。