PHP Foreach循环+ PDO
问题描述:
我正在尝试为我正在编写的Web应用程序设置一个电子邮件“系统”。漂亮得多,如果你在用户表的作用是PHP Foreach循环+ PDO
和您的帐户状态
'激活'
那么当一个新用户注册,或发送登录请求所有管理员将通过电子邮件发送。到目前为止,我只是对电子邮件进行了硬编码,但当涉及到营销应用程序时,公司不希望进入代码来更改电子邮件。所以我试图做到“动态”
我的模型大部分要感谢托马斯! :
{
$sql = "SELECT * from users WHERE status = 'Activated' and role = 3";
$admin_email = $this -> db -> conn_id -> prepare($sql);
$admin_email -> execute();
$emails = array();
if ($admin_email)
{
if ($admin_email -> rowCount() > 0)
{
foreach ($admin_email -> fetchall() as $row)
{
$emails[] = $this -> encrypt -> decode($row['email']);
}
return $emails;
}
}
}
和控制器:
{
$this -> load -> model('login_model');
$this -> load -> library('email');
$this -> load -> library('encrypt');
$emails = $this -> login_model -> admin_email();
$first = $this -> input -> post('fname');
$last = $this -> input -> post('lname');
$email = $this -> input -> post('email');
$this -> email -> from($email);
$this -> email -> to($emails);
$this -> email -> reply_to($email);
$this -> email -> subject('' . $first . ' ' . $last . ' Account Request');
$this -> email -> message('{unwrap}Hello this is ' . $first . ' ' . $last . ', I am requesting to be added to the staff log-in.{/unwrap}');
if (!$this -> email -> send())
{
$this -> session -> set_flashdata('email', 'Email Was Not Sent!');
$this -> request_account();
} else
{
$this -> session -> set_flashdata('login', 'Request Sent!');
redirect('login_controller/index', 'location');
}
}
只是从我的观察深入到这个更多:
- 第一行返回的作品就好了,但是出于测试目的,我有两个管理员帐户,就像我刚才所说,第一个只收到电子邮件。并说如果我删除第一行(第一个管理员),然后第二个得到它。所以我觉得我的foreach失败了,但我不知道为什么甚至是如何纠正我的错误。
如果任何人能告诉我什么,我做错了什么,这将是巨大的,
答
你的函数只返回一个单一的电子邮件不管,所以你可能想尝试
$sql = "SELECT email from users WHERE status = 'Activated' and role = 3";
$admin_email = $this -> db -> conn_id -> prepare($sql);
$admin_email -> execute();
$emails = array(); // initialize empty array
if ($admin_email)
{
$encryptedEmails = $admin_email->fetchAll();
foreach ($encryptedEmails as $row)
{
$emails[] = $this->encrypt->decode($row['email']); // insert the email at the end of the array
}
}
return $emails;
答
你ADMIN_EMAIL功能看起来有点怪
- 你调用PDO声明变量
$admin_email
,而它不包含任何电子邮件。它使您的代码非常自我模糊。 - 您正在使用try..catch操作符不应该使用的方式。
- 太多过度
if
小号 - 四大皆空到
$row['email']
- 有一些奇怪的
decode()
功能我怀疑是无用的或基于一些错误的假设。
所以,我决定重写这个功能更明智的方式
function admin_email()
{
$sql = "SELECT email from users WHERE status = 'Activated' and role = 3";
$stm = $this->db->conn_id->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
它将返回管理电子邮件的数组。
答
什么(编辑:删除了我的第一个答案....)
也许(我不是当然)你不应该在你foreach循环中使用两个变量。
编号:http://php.net/manual/fr/control-structures.foreach.php
如果你这样做:
foreach ($admin_email -> fetch() as $row)
{
$row = $row['email'];
}
$email = $this -> encrypt -> decode($admin_email);
你编码的邮件现在应该$ ADMIN_EMAIL数组中....作为在foreach一个处理$ ADMIN_EMAIL阵列项目之一,并有将其返回给数组(而不是简单的字符串变量)
然后检查您的解码函数是否可以处理数组。
更改此$ dbemail = $ row ['email'];'到'$ dbemail = $ row'并再次测试 – 2013-03-16 17:27:01
给出正确答案后关闭问题$ this - > logic === 0 – RaGe10940 2013-03-18 00:31:22