MySQL to Populate Foreach - php

I am working on rebuilding a newsletter system I wrote a while ago. The original system was based around using a flat file system, and I want to convert it over to MySQL. All I have left is to rebuild the end function. My problem is that I need to do is use a loop for every email stored in the database. I figured a each loop is the best way to do this, but how do you use MySQL and foreach together? Here's my current code:
$run = mysql_query("SELECT email FROM newsletter");
foreach ($run as $value) {
mail($value, $subject, $_POST['message'], $headers);
}
I've tried a lot of different things and nothing seems to work. I've even tried something like this:
$run = mysql_query("SELECT email FROM newsletter");
$email = mysql_fetch_array($run, MYSQL_ASSOC)
$cols = implode (', ', $email);
$run2 = mysql_query("SELECT $cols FROM newsletter");
while($emaillist = mysql_fetch_array($run2, MYSQL_ASSOC)){
foreach ($emaillist as $value) {
mail($value, $subject, $_POST['message'], $headers);
}
}
That was based off of a few other examples i seem. it doesnt give any errors, but it doesnt send the email. I would greatly appreciate some help.

You have to fetch your results. You can't use foreach, you'll want to use while.
$handle = mysql_query("SELECT email FROM newsletter");
while ($row = mysql_fetch_assoc( $handle ) )
{
mail( $row['email'], $subject, $_POST['message'], $headers);
}
http://us3.php.net/mysql_fetch_assoc

This pseudo code
$run = mysql_query("SELECT email FROM newsletter");
foreach ($run as $value) {
mail($value, $subject, $_POST['message'], $headers);
}
Can be correctly rewritten as:
$result = mysql_query("SELECT body, emailaddress, subject FROM emails");
if (!$result) { die('error in mysql_query: '.mysql_error())}
while ($row = mysql_fetch_array($result) {
$body = $row['body'];
$address = $row['address'];
$subject = $row['subject'];
//do stuff with that data.
//never use $_POST data directly, always feed it though `htmlentities`
//before outputting it (screen or email)
//or through mysql_real_escape_string() before inputting it in a DB.
$echo htmlentities($body); //sanitize your output or suffer XSS-attacks
.....
}
If you want to use the output of one SELECT as the input of another select do not use a loop but use a join instead:
SELECT e.body, e.subject, e.header, e.whatever FROM emails e
INNER JOIN newsletter n ON (n.id = e.newsletter_id)
WHERE n.id = 1466

Related

How can I check it appears twice and keep the email address from the database in the foreach loop?

Hello i have one selection from database and all records i store in variable $list now.. In my database i have more account with same email address how to store in variable $list one of this..
I have this code:
<?php foreach($list as $li){
echo $li['email'].'<br>';
}?>
And in mysql i have this:
public function getEmailAddress(){
$sql = "SELECT email FROM account.account";
$stmt=$this->o_db->prepare($sql);
$stmt->execute(array(':apply' => $apply));
$result = $stmt->fetchAll();
return $result;
}
In query mysql selection I need a condition or in php code?
If what you are asking is a way to skip any duplicate email addresses, here is what you can do.
Just use the DISTINCT keyword in your query.
$sql = "SELECT DISTINCT email FROM account.account";
Alternatively, you could use PHP.
<?php
$processed_emails = [];
foreach($list as $li){
$email = $li['email'];
if(!in_array($email, $processed_emails)) {
echo "{$email}<br>";
$processed_emails[] = $email;
}
}
?>
Alternatively, you could use PHP's array_unique() function.
<?php
$list = array_unique($list);
foreach($list as $li){
echo $li['email'].'<br>';
}
?>
Note:
Your code is likely failing because of this: $stmt->execute(array(':apply' => $apply));. You are sending a parameter with your query, but your query has no parameters. Since you have no parameters, you also do not need $stmt=$this->o_db->prepare($sql);.
Your code should then be:
$sql = "SELECT email FROM account.account";
$stmt=$this->o_db->query($sql);
$result = $stmt->fetchAll();

php var inside database table

i want to know if is possible to insert a var inside php
mysql table message i inserted in column header
"This is $Header From USA"
on my php page i have set
$Header = 'Adam';
so what i want to do is if i call mysql and and get the row from message table
and echo it
$result = mysql_query("SELECT * FROM `message`");
while ($row = mysql_fetch_array($result)) {
$msg = $row['header']);
}
echo $msg;
it should echo
This is Adam From USA
is this possible ?
Thank you
$result = mysql_query("SELECT * FROM `message`");
while ($row = mysql_fetch_array($result)) {
echo 'This is '.$row['header'].' From USA';
}
While the answers would be highly opinionated, a quick and dirty solution would be to use str_replace to parse out the desired replacement text.
$Header = 'Adam';
$result = mysql_query("SELECT * FROM `message`");
while ($row = mysql_fetch_array($result)) {
$msg = str_replace('$Header', $Header, $row['header']);
//use single quotes to ensure the variable data is not used instead.
}
echo $msg;
This is under the impression that the variable names are known, instead of needing to be eval'd, which is discouraged.

Splitting a php array from mysql query

I have been working on this for hours on end trying to split the resultant mysql query into their usable variables and I just don't know what I am doing incorrectly. I no longer get the resource ID# but now all I get is "array" from the variables when I print_r. I am trying to get the 3 fields from the select statement in their own array and use the values. I have been pulling my hair out trying to get this to create usable data. Any help is greatly appreciated as I feel I could spend many, many more hours tinkering and just seem to be on the wrong track.
$Query = "SELECT guardian.Email, child.CFName, guardian.FName
FROM child
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum';";
$result = mysql_query($query);
$test = mysql_fetch_array($result, MYSQL_BOTH);
print_r('this is the test '.$test."<br/>");
while($row = mysql_fetch_assoc($test, MYSQL_BOTH))
{
print_r('this is the row '.$row."<br/>");
foreach($row as $rows)
{
$info = mysql_fetch_assoc($rows, MYSQL_BOTH);
$Email = $info['0'];
$FName = $info['1'];
$CFName = $info['2'];
}
}
Thank you very much for your assistance thus far. With a combination of everyone's help I have been able to pull the values from the first level of the array with the following code :
$query = "SELECT guardian.Email, guardian.FName, child.CFName
FROM guardian
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum';";
$result = mysql_query($query);
$info = mysql_fetch_array($result);
$Email = $info['0'];
$FName = $info['1'];
$CFName = $info['2'];
However, that is only returning me 1/3rd of the data as each account has 3 guardian email addresses related to it. Where I should be getting about 2000 rows returned, I am only getting 670. That is why I was nesting another layer inside the orginal posting and why I was attempting to pull a fetch_assoc from itself. If you cannot pull an array from itself, how do you "de-nest" so to speak? Any and all help is greatly appreciated.
$emQuery = "SELECT guardian.Email, child.CFName, guardian.FName
FROM child
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum'";
$result = mysql_query($query);
$Email = array();
$FName = array();
$CFName = array();
$test = mysql_fetch_array($result, MYSQL_BOTH);
print_r('this is the test '.$test."<br/>");
while($row = mysql_fetch_assoc($test, MYSQL_BOTH))
{
echo 'this is the row ';
print_r($row);
echo '<br/>';
//$info = mysql_fetch_assoc($rows, MYSQL_BOTH);
$Email[] = $info['Email'];
$FName[] = $info['FName'];
$CFName[] = $info['CFName'];
}
To the best of my understanding this is what you are trying to do.
Some highlights:
print_r can only get a reference to a valid php array, no strings included.
mysql_fetch_assoc fetches a line out of a result set referenced by a variable, and then moves the reference to point to the next row.
You cannot call this function on a the result of it self, as it is not valid syntax.
In general, you'll be better off using PDO or mysqli_ functions at least, as it is by far more secure, by allowing you to use parameter binding instead of just using use input as part as your SQL.
You should just loop through the rows of your result once like so:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// print_r($row); Debug here if you want.
$Email = $row['Email'];
$FName = $row['FName'];
$CFName = $row['CFName'];
}
Note: You were providing a second parameter to mysql_fetch_assoc() which only takes one parameter (the result from a query). See the doc here.
mysql_fetch_array() takes another parameter that specifies what type of array to return.
Generalized PDO example out of a project of mine ($sql would be your $Query string):
$qry = $pdo->query($sql);
$all=array();
$idx=0;
while($fields=$qry->fetch( 'PDO::FETCH_ASSOC' )){
$all[key($fields)][$idx]=$fields[key($fields)];
while(next($fields)!==false){
$all[key($fields)][$idx]=$fields[key($fields)];
}
$idx++;
}
The $all variable will hold an array which in turn holds an array for each of the columns you've selected.
Like that you can do neat things like array_combine($all['Email'],$all['Fname']) and you'd get an array where the key is the Email column and the value would consist of the Fname column.

how to echo a populated php array

I have this code:
<?php
$result_array1 = array();
$sql1 = "SELECT * FROM `test_thing`";
$result1 = mysql_query("$sql1") or die($sql1.mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$result_array1[] = $row1['email'];
}
$sentmail = mail($result_array1,$subject,$message,$header);
?>
My problem is that if I place the mail function inside the loop, the user receives many emails instead of one, and if I place it out of the loop, no email is sent. My aim is to send only 1 email to each user, but that email should containt in it many mixed emails. I have read in other forums that it can be done using arrays. Maybe there is a mistake with the codes.
Any suggestions?
Thanks
try this
<?php
$result_array1 = array();
$sql1 = "SELECT * FROM `test_thing`";
$result1 = mysql_query("$sql1") or die($sql1.mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$result_array1[] = $row1['email'];
}
$email = implode(",",$result_array1); // $email = "one#example.com,two#example.com,three#example.com"
$sentmail = mail($email,$subject,$message,$header);
?>
The first parameter of the mail can be a single email id or email ids separated by commas. Which means you can send the email to multiple users just using one function call.
Just use the following MySQL query:
SELECT DISTINCT email FROM `test_thing`
It will return only unique e-mail addresses from the table. That way you can use the mail() in the loop and not worry about duplicated e-mail addresses.
According to php.net: http://php.net/manual/en/function.mail.php
mail accepts a string for the to address. You could always implode(',', $result_array1)
IMHO $to parameter in mail function just one email support .if you want send to many email, change your $headers and set Bcc;
sample code:
$headers.="Bcc: ";
while($count < $count_recip){
$headers.=$recip[$count].", ";
$count ++;
}
This worked for me:
$result_array1 = array();
$sql1 = "SELECT DISTINCT * FROM `test_thing` GROUP BY `user_id`";
$result1 = mysql_query("$sql1") or die($sql1.mysql_error());
while($row1 = mysql_fetch_array($result1))
{
$result_array1[] = $row1['EmailAddress'];
}
$email = implode(",",$result_array1);
I modified some of the answers together.
There will be no duplicate emails either, atleast there wasn't for me.

In php how to display mysql results?

I have a mysql table in which I keep e-mail addresses. The structure is as follows:
id || email
However, how do I actually output those e-mail addresses, separated by commas, in php?
Thanks in advance for your help!
Use:
<?php
$query = "SELECT GROUP_CONCAT(t.email) AS emails
FROM YOUR_TABLE t"
// Perform Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['emails'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
References:
mysql_query
GROUP_CONCAT
Third hit on Google for "php mysql": http://www.freewebmasterhelp.com/tutorials/phpmysql
You probably need to read up on the basics, it's not complicated and will only take a few minutes to glance over it and get you started.
Option 1:
$sql = "SELECT GROUP_CONCAT(email ORDER BY email ASC SEPARATOR ', ') AS emails FROM emails";
$res = mysql_query($sql);
list($emails) = mysql_fetch_row($res);
echo $emails;
Option 2, so you can do more with all the emails later on:
$emails = array();
$sql = "SELECT email FROM emails ORDER BY email ASC";
$res = mysql_query($sql);
while ($r = mysql_fetch_object($res)) {
$emails[] = $r->email;
}
// as a list
echo implode(', ',$emails);
// or do something else
foreach ($emails as $email) {
// ...
}
Do something like:
while ($output = mysql_fetch_array($query_results)) {
echo $output['id'] . ", " . output['email'];
}

Categories