array is added to email address - php

i was using this codes to send newsletter to members , now the problem is that when i send emails it doesn't send . i tracked the emails in cpanel and found that the email address has the word 'array' before it . that means that when i send to 'email#domain.com' it changes to 'arrayemail#domain.com'. and this is the code :
<?php
include("../include/config.php");
include_once("../include/functions/import.php");
verify_login_admin();
$adminurl = $config['adminurl'];
$thebaseurl = $config['baseurl'];
$sql = "SELECT USERID, username, email FROM members";
$executequery = $conn->Execute($sql);
$results= $executequery->getrows();
if($_POST['submitform'] == "1")
{
if(isset($_POST['USERID']))
{
foreach($_POST['USERID'] as $key)
{
$subject = $_POST['subject'];
$sendername = $config['site_name'];
//$bodymessage = "Dear " . $_POST['username'];
//$sendmailbody = "HI". $results[$i]. $key . $results[$i].$_POST['username'] .",";
$sendmailbody .= $_POST['message'];
$sendmailbody .= "";
$from = $config['site_name'].'<'.$config['site_email'].'>';
$sendto = $results[$i]. $key.',';
mailme($sendto,$sendername,$from,$subject,$sendmailbody,$bcc);
}
}
$message = "E-Mails / Newsletters sent successfully.";
Stemplate::assign('message',$message);
}
$mainmenu = "7";
$submenu = "2";
$bodymsg = $_POST['message'];
Stemplate::assign('subject',$subject);
Stemplate::assign('bodymsg',$bodymsg);
Stemplate::assign('mainmenu',$mainmenu);
Stemplate::assign('submenu',$submenu);
Stemplate::assign('results',$results);
STemplate::display("administrator/global_header.tpl");
STemplate::display("administrator/mass_newsletter.tpl");
STemplate::display("administrator/global_footer.tpl");
?>

It looks like you are getting all rows from your query:
$results= $executequery->getrows();
^ plural
But you never actually loop over all rows, so $results[$i] will contain one complete row from the result set: An array containing the USERID, username and email.
And when you concatenate an array with a string, the array will result in the text array.
And that is assuming that $i is an integer but in your code it is not defined at all.
You probably want to loop over the result-set somewhere and if you use a foreach you will not need the $i variable at all:
foreach ($results as $result) {
// Build your e-mail addresses string?
...
}

Related

How do i successfully use function array_intersect() here?

I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}

php email reminder script issue

I am building a script that checks for dates that will expire within 7 days and sends out a email reminder to the admin owner and also update a date notified column in the database, I have got it sort of working, it updates the date notified column and sends the email out but it only lists one date in the email where as there should be two as I set two dates to expire within 7 days, can anyone help please, below is the coding I have
<?php
$db = mysqli_connect("localhost" , "", "") or die("Check connection parameters!");
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)
mysqli_select_db($db,"") or die(mysqli_error($db));
if (mysqli_connect_error()) {
die ('Failed to connect to MySQL');
} else {
/*SUCCESS MSG*/
echo '';
}
$sqlCommand = "SELECT
u.id
, domain_name_owner
, url
, DATE_FORMAT(domain_expiry_date, '%e %M %Y') as domain_expiration_date
, domain_owner_email
FROM websites u
WHERE domain_expiry_date BETWEEN CURDATE() AND CURDATE()+INTERVAL 7 DAY
";
$query = mysqli_query($db, $sqlCommand) or die (mysqli_error($db));
//fetch the data from the database
while ($row = mysqli_fetch_array($query)) {
$arr_ids[] = $row['id'];
$email = '';
$headers = "From: noreply#domain.co.uk\r\n";
$subject = "Domain Name Expiry Date(s)";
$message = '';
$id = $row['id'];
$owner = $row['domain_name_owner'];
$email = $row['domain_owner_email'];
$message = "Domain Name Owner: {$row['domain_name_owner']} \n\n";
$message .= "Your Domain Name {$row['url']} expiry date is: {$row['domain_expiration_date']}\n";
$to = $email;
$sendmail = mail($to, $subject, $message, $headers);
if ($sendmail) {
echo nl2br($message);
echo "<b>Email Successfully Sent</b><br><br>";
} else {
echo "<b>Error in Sending of Email to $to</b><br><br>";
}
}
if (isset($arr_ids)){
$sql = "UPDATE websites SET date_notified_of_domain_expiry = NOW() WHERE id IN (";
$sql .= implode("," , $arr_ids);
$sql .= ");";
print $sql;
}
//$db->query($sql);
$db->query($sql) or die(mysqli_error($db));
// Free the results
mysqli_free_result($query);
//close the connection
mysqli_close($db);
?>
Thank you in advance
Your Script is working fine, it should send one email per expiry date (based on your code), if the domain owner owns two domains, he will receive two separate emails that each one of them is related to a certain domain.
If you want to send the two domains on the same email, use the below script:
<?php
$db = mysqli_connect("localhost" , "", "") or die("Check connection parameters!");
// Optionally skip select_db and use: mysqli_connect(host,user,pass,dbname)
mysqli_select_db($db,"") or die(mysqli_error($db));
if (mysqli_connect_error()) {
die ('Failed to connect to MySQL');
} else {
/*SUCCESS MSG*/
echo '';
}
$sqlCommand = "SELECT
u.id
, domain_name_owner
, url
, DATE_FORMAT(domain_expiry_date, '%e %M %Y') as domain_expiration_date
, domain_owner_email
FROM websites u
WHERE domain_expiry_date BETWEEN CURDATE() AND CURDATE()+INTERVAL 7 DAY
";
$query = mysqli_query($db, $sqlCommand) or die (mysqli_error($db));
//fetch the data from the database
$message = '';
$email = '';
$prev_Email ='';
while ($row = mysqli_fetch_array($query)) {
$arr_ids[] = $row['id'];
$prev_Email = $email;
$headers = "From: noreply#domain.co.uk\r\n";
$subject = "Domain Name Expiry Date(s)";
$id = $row['id'];
$owner = $row['domain_name_owner'];
$email = $row['domain_owner_email'];
if($prev_Email == ""){
$prev_Email = $email;
}
if($email == $prev_email && $email != ""){
$message. = "Domain Name Owner: {$row['domain_name_owner']} \n\n";
$message .= "Your Domain Name {$row['url']} expiry date is: {$row['domain_expiration_date']}\n";
}else{
if($prev_Email != ""){
$to = $prev_Email;
$sendmail = mail($to, $subject, $message, $headers);
if ($sendmail) {
echo nl2br($message);
echo "<b>Email Successfully Sent</b><br><br>";
} else {
echo "<b>Error in Sending of Email to $to</b><br><br>";
}
$message = "Domain Name Owner: {$row['domain_name_owner']} \n\n";
$message .= "Your Domain Name {$row['url']} expiry date is: {$row['domain_expiration_date']}\n";
}
}
}
if (isset($arr_ids)){
$sql = "UPDATE websites SET date_notified_of_domain_expiry = NOW() WHERE id IN (";
$sql .= implode("," , $arr_ids);
$sql .= ");";
print $sql;
}
//$db->query($sql);
$db->query($sql) or die(mysqli_error($db));
// Free the results
mysqli_free_result($query);
//close the connection
mysqli_close($db);
?>

While submitting a form I check if there the e-mail isnt already in the sql database but it doesnt work

I'm using a fetchAll and a for loop to do the trick. In the if statement with $validate as result I tried numbers, boolean and now strings to get the result. Nothing worked so far. Here is my code:
$groep_naam = $_POST['groep'];
$naam = $_POST['naam'];
$adres = $_POST['adres'];
$mail2 = $_POST['mail2'];
$pass1 = md5($_POST['pass1']);
$pass2 = md5($_POST['pass2']);
$select = $db->prepare("SELECT * FROM deelnemers");
$select->execute();
$result = $select->fetchAll();
$len = count($result);
for ($x=0;$x<$len;$x++) {
$mail1 = $_POST['mail1'];
$db_mail = $result[$x][mail];
if ($db_mail != $mail1) {
$validate = "true";
}
if ($db_mail == $mail1) {
$validate = "false";
}
}
if (isset($_POST['submit'])) {
if ($mail1 == $mail2 && $pass1 == $pass2) {
if ($validate == "true") {
$add = $db->prepare("INSERT INTO deelnemers (groep_naam, naam, adres, mail, pass, rechten) VALUES ('$groep_naam', '$naam', '$adres', '$mail1', '$pass1', 'user')");
$add->execute();
} if ($validate == "false") {
echo '
<script>
$("#duplicateEntry").modal("show");
</script>
';
}
You are doing it wrong. Instead of fetching all emails, you should do a query to check if that particular email exists in db.
Pseudocode:
$select = $db->prepare("SELECT 1 FROM deelnemers WHERE mail = :email");
$select->bindValue(':email', $_POST['mail1']);
$select->execute();
$validate = $select->rowCount() > 0; //rowCount/rowExists/whatever to check if the query returned anything
Looking at your current code, probable mistake is on line
$db_mail = $result[$x][mail];
It probably should've been
$db_mail = $result[$x]['mail'];
Another thing, you loop through all emails comparing them with the one from request, so even if you find the one email matching it, later in another loop you rewrite your $validate value.

Update a mysql table with session generated information

I'm currently doing a Web Programming module at university and have been having trouble with some of the homework set. We are meant to insert code that updates our current mysql table with new information (gender, age, email, comment). This information needs to be inserted into the row of each persons session generated ID (currID). How do we code for the updated information to be inserted into a session-specific row?
<?php
session_start();
include('muqHeader.html');
include('commonSrc.php');
include('../shareCode/mysqlLink.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST'):
// update the mf record
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
}else{
echo "Not a valid email address";
}
if(filter_var($_POST['comment'], FILTER_SANITIZE_STRING)){
}else{
echo "Text includes invalid characters";
}
$gender = $_POST['gender'];
$age = $_POST['age'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$currID = $_SESSION['currID'];
if ($_POST['submit']){
$sql = "UPDATE muq
SET (gender='$gender', age = '$age', email = '$email', comment = '$comment')
WHERE (muqID = '$currID')";
}
if (#mysqli_query($link, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . #mysqli_error($link);
}
else:
$useTime = implode(',', $_SESSION['useTime'] );
$usedM = implode( ',', $_SESSION['usedM'] );
$tmp = array();
for($i=0; $i < count($_SESSION['freqRate']); $i++) {
$tmp[$i] = implode( '', $_SESSION['freqRate'][$i] ); // empty string as 'glue'
}
$freqRate = implode( ',', $tmp );
$dateTime = $_SESSION['dateTime'];
$taskTime = (time() - $_SESSION['startTime']) / 60; //in minutes
$sql = "INSERT INTO muq
(dateTime, taskTime, useTime, usedM, freqRate)
VALUES ('$dateTime', '$taskTime', '$useTime', '$usedM', 'freqRate')";
$link = connectDB();
#mysqli_query( $link, $sql );
$_SESSION['currID'] = #mysqli_insert_id($link);
#mysqli_close($link);
?>
Well, before answearing your question, here is some coding rules you need to respect:
1- You don't have to use more lines than what you need. This means you don't have to do an an empty "if" using 4 lines if you can do it in 2 lines.
Example:
Instead of:
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
}else{
echo "Not a valid email address";
}
You can do:
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
echo "Not a valid email address";
Second thing, to update a row in a database, you need an ID. This the key you are going to use to tell your db engine which row you are going to update because if not "he" will not know which row "he" should update (I'm considering the db engine as a person like me and you :D )
So, you need to inject that key (account ID or whatever) in your session so that you can use later when updating your database by telling you db engine that "he" needs to update that row identified by that key.

Setting the "name" of the "sender" of an email

The code below is supposed to send out an email if a comment is made on a submission where a certain condition is met (subcheck = 1). It works fairly well.
However, the "name" of the sender that shows up is two 7-digit numbers separated by a dot. How could I make the name of the sender something else, like no-reply#domain.com for example?
Thanks in advance,
John
$querye = mysql_query("SELECT subcheck FROM submission WHERE subcheck = '1' AND submissionid = '$submissionid' ");
if (mysql_num_rows($querye) == 1)
{
$email_query = "SELECT email FROM login WHERE username = '$submittor'";
$result = mysql_query($email_query);
if (!$result) {
trigger_error('Invalid query: ' . mysql_error()." in ".$email_query);
}
if($row = mysql_fetch_assoc($result)) {
$mailaddress = $row['email'];
$queryem = mail($mailaddress, "Someone has commented on your submission
$submission.", $comment, "no-reply#domain.com");
}else{
// no rows found.
}
}
else
{
//your subcheck is not 1 / nothing was found
}
Just add FROM: so your code will be like this:
mail($mailaddress, "Someone has commented on your submission
$submission.", $comment, "FROM: no-reply#domain.com");

Categories