$row["email"] not pulling from my SELECT statement into phpmailer field [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 months ago.
I am using a select statement to pull data from my DB using a where clause and limited to 1, then i am trying to put the addresses it has pulled into the sendto field on phpmailer.
I have updated the question so the full code is here, i am still unable to pull up the echo from the var that i entered to collect the emails from the list.
<?php
$servername = "localhost";
$username = "####";
$password = "####";
$dbname = "####";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT email FROM emails WHERE status = 'new' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["email"]. " ";
}
} else {
echo "0 results";
}
$sql = "UPDATE emails SET status='done' WHERE status = 'new' LIMIT 1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$var_email = $row["email"];
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
Class SendMail{
function send(){
$mail = new PHPMailer(true);
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = '####'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = '####'; //SMTP username
$mail->Password = '####';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465;
//Recipients
$mail->setFrom('info#####', '####');
$mail->addAddress($var_email);
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = '####';
$mail->Body = "####";
$mail->send();
echo 'Message has been sent';
}
}
$sendMail = new SendMail();
$sendMail->send();
$conn->close();
?>
I am hoping its a simple fix, but i feel like somewhere i have put the wrong string which is not allowing me to echo the results into the address field.
any suggestions?

take a variable and assign value to it
ex. $var_email = $row["email"];
$mail->addAddress($var_email);
try it it's working. problem is occur because of php version

Related

How to send and email to the receiver after sender (admin) submit the form to database

I'm stuck on how to uses PHPMailer. I create a simple PHP form to book a meeting room. Admin needs to log in the system and key in all details including requester email's, factory and room. After admin click 'submit', it will save to database under table 'booking'.
Now, What I want is when I clicked the submit button, It also sent an email to the user about the details that already booked.
Below is my current code:
home.php
<?php
require_once 'configPDO.php';
session_start();
if(!ISSET($_SESSION['login_user'])){
header('location:index.php');
}
$Email = $_SESSION['login_user'];
$sql = $conn->prepare("SELECT * FROM staff WHERE Email='$Email'");
$sql->execute();
$fetch = $sql->fetch();
if(ISSET($_POST['submit'])){
if($_POST['Requested_by'] != "" || $_POST['Factory'] != "" || $_POST['Room'] != ""){
try{
$Requested_by = $_POST['Requested_by'];
$Factory = $_POST['Factory'];
$Room = $_POST['Room'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `booking` VALUES ('', '$Requested_by', '$Factory', '$Room')";
$conn->exec($sql);
}catch(PDOException $e){
echo $e->getMessage();
}
$conn = null;
header('location:index.php');
}else{
echo "
<script>alert('Please fill up the required field!')</script>
<script>window.location = 'registration.php'</script>
";
}
}
?>
sendmail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Mailer/Exception.php';
require 'PHPMailer/Mailer/PHPMailer.php';
require 'PHPMailer/Mailer/SMTP.php';
require_once 'configPDO.php';
session_start();
$sendermail = '';
$sendername = '';
$senderpassword = '';
$receiveremail = '';
$receivername = '';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.office365.com'; //gmail SMTP server
$mail->SMTPAuth = true;
$mail->Username = $sendermail; //username
$mail->Password = $senderpassword; //password
$mail->SMTPSecure = 'TLS';
$mail->Port = 587; //smtp port
$mail->setFrom($sendermail, $sendername);
$mail->addAddress($receiveremail, $receivername);
$mail->isHTML(true);
$mail->Subject = 'E-booking';
$mail->Body = '<h3>Dear '.$receivername.',</h3>';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
}
?>
Please help me. thanks

Sending Bulk emails through phpmailer

I am using phpmailer to send bulk emails to my subscribers but I am facing a terrible problem that is when I send emails to my subscribers, each subscriber is getting the same email more than once. some are getting 4 times and some are getting 14 times.
I am fetching subscriber emails where flag = 0 through Mysql table and at the end of the while loop I am updating subscriber flag to 1. I know its a issue of loop but I don't know where I am doing wrong or even not sure should I used while loop or something else to fix this issue. Any help would be highly grateful to me.
here is my code:
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$link= mysqli_connect("$db_host","$db_username","$db_pass", "mydb") or die ("could not connect to mysql");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Simply:
//Load Composer's autoloader
require 'vendor/autoload.php';
if(isset($_POST['send'])){
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
$query = "select customer_id, customer_name, customer_email from subscribers where flag_email = 0";
$result = mysqli_query($link, $query) or die("No customer in the table");;
while($values = mysqli_fetch_array($result)){
$id = $values['customer_id'];
$name = $values['customer_name'];
$toemail = $values['customer_email'];
//Server settings
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp server'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('username', 'username');
$mail->addReplyTo('myemail', 'name');
$mail->addBCC(''.$toemail.'', ''.$name.'');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'Here is the message';
$mail->send();
echo 'Message has been sent';
$upd_query = "update subscribers set flag_email = 1 where customer_id = ".$id."";
$result= mysqli_query($link, $upd_query);
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
This is happening because you're not clearing the to addresses each time around your loop - notice the method is called addAddress, not setAddress, and it does what that suggests. You need to call $mail->clearAddresses(); at the end of your loop to reset it. You're doing things mostly right otherwise, but there are a few things you can do to improve efficiency, mainly using keep alive and setting all the properties that are common to all messages before your loop.
You can see all this working in the mailing list example provided with PHPMailer.
The issue i'm seeing is, the replacement of result variable with update output inside while loop. Please use different variable name inside while loop
$upd_query = "update subscribers set flag_email = 1 where customer_id = ".$id."";
$updateResult= mysqli_query($link, $upd_query);
mailer object creation can be move inside to while loop
$query = "select customer_id, customer_name, customer_email from subscribers where flag_email = 0";
$result = mysqli_query($link, $query) or die("No customer in the table");;
while($values = mysqli_fetch_assoc($result)){
$mail = new PHPMailer(true);
....
}

PHP - Set a Variable within while loop

I'm currently trying to set a variable within a while loop equal to different values of an array. I have my select statement setup so that it pulls the information successfully and can be displayed by echoing the relevant classes. However, if I try to set the rows equal to a variable on the second pass it doesn't run and completes the while loop.
$username = "xxx";
$password = "xxx";
$hostname = "xxx";
$database = "xx";
$dbhandle = mysqli_connect($hostname, $username, $password, $database) or die("Unable to connect to MySQL");
$conn = new mysqli($hostname, $username, $password, $database);
$date = "1996-03-12 12:03:00";
$selectcmd = "SELECT starttime, endtime, partner, worklist, serviceloss, servicereference, siteaddress, ticketref FROM work WHERE starttime='$date'";
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$result = $conn->query($selectcmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$body = $row["starttime"].$row["endtime"];
require "mail.php";
}
} else {
echo "No Mail To Send";
}
$conn->close();
mail.php is the PHPMailer function and sends emails fine.
I know the issue is that I'm trying to set a variable within the while loop. However, I'm not sure how to overcome this. I've attempted to unset the body at the end of the while loop.
mail.php for those who asked:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';
$mail = new PHPMailer();
try {
$mail->isSMTP();
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->Username = 'user#example.com';
$mail->Password = 'secret';
$mail->Port = 25;
$mail->setFrom('test#test.com', 'test');
$mail->addAddress('joe#example.net');
$date = "today";
$mail->isHTML(true);
$mail->Subject = 'Important Notification';
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
die();
} catch (Exception $e) {
die();
}
My issue was as #PatrickQ advised.
The die() function was causing the script to stop running altogether. I removed this from mail.php and then moved the require 'mail.php' to outside the while loop. I then added the $mail->send(); function to the while loop.
Everything is as I wish :)

Unable to fetch data from table

I am testing a form that asks for a users email and then sends him his name,surname and cellphone number. Now everything is working. It selects the user depending on the email entered. It sends the email.
The only issue I am having is how do I insert the data from the table into the email thats sending to him?
Eg.$mail->Body = "Your company details are: " Name,Surname,Cellphone;
thats the issue I am currently facing. My full code is below.
I am still quite new at PHP so if this is a general/common error, then I apologise.
<?php
error_reporting(1);
ini_set('error_reporting', E_ALL);
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="****"; // Mysql password
$db_name="Username"; // Database name
$tbl_name="Name"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password, $db_name);
// Define $username and $password
$username=$_POST['user_name'];
$sql="SELECT * FROM $tbl_name WHERE Name='$username'";
$result=mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if ($count > 0)
{
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "****"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "****"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "****"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "Test";
$mail->FromName = "Test";
$mail->AddAddress($username, "");
$mail->isHTML(true);
$mail->Subject = 'Out Of Office Password';
$mail->Body = "Your Out Of Office password: ";
if(!$mail->Send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit();
}
else
{
echo 'Email Sent Successfully!';
}
}
?>
The form:
<center>
<html>
<head>
<title>User Information</title>
</head>
<body>
<form action="check-user.php" method="POST">
<h3>User Information</h3>
Email: <input type="text" name="user_name"><br>
<input type="submit" name="submit" value="Send Info">
</form>
</body>
</html>
</center>
First make your connection valid
$conn = mysqli_connect($host, $username, $password, $db_name)
// if u get connection valid message delete this if statement this is just for testing your connection
if ($conn) {
echo 'connection valid';
} else {
echo 'connection invalid ' . mysqli_error($conn);
}
And u don't need this
echo "Connected to MySQL<br />";
mysqli_select_db("$db_name") or die(mysqli_error());
echo "Connected to Database<br />";
Change this line
$result=mysqli_query($conn, $sql);
And this one
if ($count > 0) {
And because u new to php, i think u need atleast learn how to connect to database, check for error_reporting, get/update/insert/delete data into database.
And my opinion is if u are starting to learn use PDO with prepared statements because it safe. This mysqli without escaping will get u trouble with security.
EDIT:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="****"; // Mysql password
$db_name="Username"; // Database name
$tbl_name="Name"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password, $db_name) or die(mysqli_error($conn));
if (isset($_POST['submit']))
{
// Define $username
$username = $_POST['user_name'];
$sql = "SELECT * FROM $tbl_name WHERE Name='$username'";
$result = mysqli_query($conn, $sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
if ($count > 0 )
{
// get data from user
$data = mysqli_fetch_array($result, MYSQLI_ASSOC);
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "****"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "****"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "****"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "Test";
$mail->FromName = "Test";
$mail->AddAddress($username, "");
$mail->isHTML(true);
$mail->Subject = 'Your Company Details';
$mail->Body = "Your company details are: Name: = " . $data['Name'] . ", Surname: " . $data['Surname'] . ", Cellphone: " . $data['Cellphone'];
if(!$mail->Send())
{
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit();
}
else
{
echo 'Email Sent Successfully!';
}
}
ob_end_flush();
?>

How to send email to address fetched from database via php mailer

I have made page where the user enters the data & send email.First i want to insert data into db & then trigger mail to registered email id.Till now i was manually typing the email id. What should be done to fetch the email id from database & send it.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$sname=$_SESSION['usr_name'];
$room = mysqli_real_escape_string($conn, $_POST['txtrname']);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$dept = mysqli_real_escape_string($conn, $_POST['txtdept']);
$purpose = mysqli_real_escape_string($conn, $_POST['txtpurpose']);
$attendee = mysqli_real_escape_string($conn, $_POST['attendee']);
$date = mysqli_real_escape_string($conn, $_POST['txtdate']);
$btime = mysqli_real_escape_string($conn, $_POST['btime']);
$etime = mysqli_real_escape_string($conn, $_POST['etime']);
$sql="INSERT INTO bookingdetails (room,name,department,purpose,attendee,date,starttime,endtime,status_id)VALUES('$room','$name','$dept','$purpose','$attendee','$date','$btime','$etime','2')";
$res = mysqli_query($conn,"SELECT emailid FROM newuser WHERE username='$sname'");
$row = mysqli_fetch_assoc($res);
$to = $row["emailid"];
require('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$subject = "Bookig Details";
$content = "<b>Hello $name. Your Booking Details are as follow. Room : $room Date : $date Start Time : $btime End Time : $etime</b>";
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "no";
$mail->Port = 26;
$mail->Username = "admin";
$mail->Password = "###";
$mail->Host = "59.68.1.101";
$mail->Mailer = "smtp";
$mail->SetFrom("admin#hitechplast.in", "Admin");
$mail->AddReplyTo("admin#hitechplast.in", "Admin");
$mail->AddAddress($to);
$mail->Subject = $subject;
$mail->WordWrap = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
if (mysqli_query($conn,$sql))
{
echo "Record added";
}
else
{
die('Error: ' . mysqli_error());
}
?>
I Think the problem is with session start.
You use this peice of session
$sname=$_SESSION['usr_name'];
and you forget to start session
use
session_start();
at the top of your page
$res = mysqli_query($conn,"SELECT emailid FROM newuser WHERE username='$sname'") or die(mysqli_error($conn));
if($res && mysql_num_rows($res)>0)
{
$data = mysql_fetch_assoc($res);
$userEmail = $data['emailid']; // now this is your email id variable for user's email address.
require('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer();
$subject = "Bookig Details";
$content = "<b>Hello $name. Your Booking Details are as follow. Room : $room Date : $date Start Time : $btime End Time : $etime</b>";
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "no";
$mail->Port = 26;
$mail->Username = "meetingroom.admin";
$mail->Password = "###";
$mail->Host = "59.68.1.101";
$mail->Mailer = "smtp";
$mail->SetFrom("admin#hitechplast.in", "Admin");
$mail->AddReplyTo("admin#hitechplast.in", "Admin");
$mail->AddAddress($userEmail); // you can't pass php variables in single goutes like '$userEmail'.
$mail->Subject = $subject;
$mail->WordWrap = 80;
$mail->MsgHTML($content);
$mail->IsHTML(true);
}
try this. Your changes seem correct. Only you are passing email variable $to in single quotes. Hope it helps.
You need to fetch the assoc array, not the array.
$row = mysqli_fetch_assoc($res);

Categories