How to send data in email using HTML table & php - php

I'm trying to send data from database in the form of a HTML table when user click submit button. I'm able to receive the email but only table received. It doesn't seem database data. I want to email a table with data in database. Here is my code.
<?php
require '../Mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
//$mail->SMTPSecure = 'tls';
//$mail->SMTPAuth = true;
$mail->Host = '';
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = 'Student data';
$body = '<html>
<head>
<title></title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
color:black
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<?php
$username = "root";
$password = "";
$host = "localhost";
$connector = mysqli_connect("$host,$username,$password");
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysqli_select_db("school"," $connector");
or die("Unable to connect");
//execute the SQL query and return records
$result = mysqli_query("SELECT*FROM student ");
?>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>class</th>
<th>address</th>
<th>comment</th>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){?>
<tr>
<td><?php echo $row["id"] ?></td>
<td><?php echo $row["name"]?></td>
<td><?php echo $row["age"] ?></td>
<td><?php echo $row["class"] ?></td>
<td><?php echo $row["address"] ?></td>
<td><?php echo $row["comment"] ?></td>
</tr>
<?php }
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html> ';
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "ERROR: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}

Thanks for everyone, who answer to my question. Here is the working code for my system.
<?php
require '../Mailer/PHPMailerAutoload.php';
$username = "root";
$password = "";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysql_select_db("school", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result= mysql_query("SELECT * FROM student ORDER BY id DESC limit 1");
$mail = new PHPMailer;
$mail->isSMTP();
//$mail->SMTPSecure = 'tls';
//$mail->SMTPAuth = true;
$mail->Host = '';
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = 'Student Data';
$body = "<html>
<head>
<title>Student Data</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
color:black
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Class</th>
<th>Address</th>
<th>comment</th>
</tr>
</thead>
<tbody>";
while( $row = mysql_fetch_assoc( $result ) ){
$body.= "<tr>
<td>".$row['id']."</td>
<td>".$row['name']."</td>
<td>".$row['age']."</td>
<td>".$row['class']."</td>
<td>".$row['address']."</td>
<td>".$row['comment']."</td>
</tr>";
}
$body.="</tbody></table></body></html>";
?>
<?php mysql_close($connector); ?>
<?php
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "ERROR: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}
?>

Above your mysql connection data ($username, ...) is still a php opening tag.

Your code is all wrong, you're opening php tags inside a php tag.
Also you were using mysqli_ the wrong way, then trying to close with mysql_ .
Here, I fixed it for you:
<?php
require '../Mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
//$mail->SMTPSecure = 'tls';
//$mail->SMTPAuth = true;
$mail->Host = '';
$mail->Port = ;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('');
$mail->addAddress('');
$mail->isHTML(true);
$mail->Subject = 'Student data';
$body = '<html>
<head>
<title></title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: left;
padding: 8px;
color:black
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
';
$username = "root";
$password = "";
$host = "localhost";
$connector = mysqli_connect($host,$username,$password, "school");
or die("Unable to connect");
echo "Connections are made successfully::";
//execute the SQL query and return records
$result = mysqli_query($connector, "SELECT*FROM student ");
$body .='
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>class</th>
<th>address</th>
<th>comment</th>
</tr>
</thead>
<tbody>';
while( $row = mysqli_fetch_assoc($connector, $result ) ){
$body .= "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['age']}</td>
<td>{$row['class']}</td>
<td>{$row['address']}</td>
<td>{$row['comment']}</td>
</tr>"
}
$body .='
</tbody>
</table>
</body>
</html> ';
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "ERROR: " . $mail->ErrorInfo;
} else {
echo "SUCCESS";
}

Related

PHPMailer doesn't send mail even after including SMTP.php

For some strange reason my PHP login system that sends a confirmation email to activate your account but it doesn't send anything.
<?php
$error = NULL;
require "phpmailer/class.phpmailer.php";
require "phpmailer/class.smtp.php";
require "phpmailer/PHPMailerAutoload.php";
if(isset($_POST['submit'])) {
//Form Data GET
$u = $_POST['u'];
$p = $_POST['p'];
$p2 = $_POST['p2'];
$e = $_POST['e'];
//Throw Username too short error
if(strlen($u) < 5){
$error = "(!) Your username must be at least 5 characters.";
}elseif($p2 != $p) {
//Throw password pair error.
$error .= "(!) Your passwords do not match :/";
}else{
//200 [OK]
//Establish Connection to Database
$mysqli = NEW MySQLi('localhost','root','','test');
//Convert special chars.
$u = $mysqli->real_escape_string($u);
$p = $mysqli->real_escape_string($p);
$p2 = $mysqli->real_escape_string($p2);
$e = $mysqli->real_escape_string($e);
//Generate Verification Key
$vkey = md5(time().$u);
//Insert account into database
$p = md5($p);
$insert = $mysqli->query("INSERT INTO accounts(username,password,email,vkey)
VALUES('$u','$p','$e','$vkey')");
if($insert){
//Start PHPMailer
$mail = new PHPMailer(true);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 0; //No Debug. Set to 3 for verbose logging.
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; //Set to SSL to pass checks.
$mail->Host = "smtp.mail.com"; //Set to mail.com server, it has ssl, smtp, and it's free. If you'd like to use gmail, use smtp.gmail.com
$mail->Port = 465; //SSL/TLS Port for mail.com and gmail.com
//FILL WITH YOUR DETAILS
$mail->Username = 'example#mail.com';
$mail->Password = 'example';
//DON'T SET TO SENDER ADDRESS WILL FAIL SPF CHECKS!!!
$mail->SetFrom('example#mail.com', 'example');
$mail->AddAddress($e);
//Send the email.
$mail->Subject = trim("Email Verifcation");
$mail->isHTML(true);
//The Message
$mail->Body = '<h1>Hi, ' . $u . '!</h1><br><p>Activate<br><p>Alternatively copy and paste this link in your browser: <br> <b>Https://localhost' . $vkey . '';
echo "<center><div class='alert success'><strong>Successfully Registered!</strong> Please check your email.</div></center>";
}
//OOPS! Throw $error.
echo $mysqli->error;
}
}
?>
In the beginning, I require the files in my PHPMailer folder, then I start PHPMailer
It stresses me out. Idk the problem. If anybody knows the solution or knows a hint of why it doesn't work that would be great. Thanks.
HTML in same file
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
.alert {
padding: 20px;
background-color: #f44336;
color: white;
opacity: 1;
transition: opacity 0.6s;
margin-bottom: 15px;
font-family: Sans-Serif;
border-radius: 15px;
}
.alert.success {background-color: #4CAF50;}
.alert.info {background-color: #2196F3;}
.alert.warning {background-color: #ff9800;}
.closebtn {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
</style>
</head>
<body>
<form method="POST" action="">
<table border="0" align="center" cellpadding="5">
<tr>
<td align="right">Username:</td>
<td><input type="TEXT" name="u" required/></td>
</tr>
<tr>
<td align="right">Password</td>
<td><input type="PASSWORD" name="p" required/></td>
</tr>
<tr>
<td align="right">Repeat Password</td>
<td><input type="PASSWORD" name="p2" required/></td>
</tr>
<tr>
<td align="right">Email Address</td>
<td><input type="EMAIL" name="e" required/></td>
</tr>
<td colspan="2" align="center"><input type="SUBMIT" name="submit" value="Register" required/></td>
</table>
</form>
<center>
<?php
echo $error ;
?>
</center>
</body>
</html>
you can probably try this
i also had an error so i had to add this line before the host
$mail->SMTPOptions=array('ssl'=>array('verify_peer'=>false,'verify_peer_name'=>false,'allow_self_signed'=>false));
but if that does not work you can try trobleshooting like this
if($mail->Send()){
}else{
var_dump($mail);
die();
}
so once you get your error logs you can probably do a google or paste your error log and maybe we can help

Erro com PHPMailer - Fatal error: Class 'PHPMailer' not found in /home/intergroup/public_html/view/envio_contato.php on line 90

This is the message i am getting on my log.
Fatal error: Class 'PHPMailer' not found in
/home/intergroup/public_html/view/envio_contato.php on line 90
But when i press crtl+g on sublime he finds the classes with means the includes are correct.
this is my code: (This text right here is just because StackOverflor dont allows me to post my question, he says i have too much code and i need to explain better and give more details, so: How can i solve this problem, like, what kind of actions can i take to debug?)
<?php
$robots = 'nao';
include '_definicoes.php';
include_once '_header.php';
$pagina_atual = 'envio_contato';
$link_encaminhar_erro = $dominio;
$link_encaminhar_concluido = $dominio;
$title = $nome_site;
$description = $description;
$keywords = $keywords;
// resposta vazia
$response = null;
// verifique a chave secreta
// $reCaptcha = new ReCaptcha($secret);
// if (isset($_POST['submit'])) {
// se submetido, verifique a resposta
// if ($_POST["g-recaptcha-response"]) {
// $response = $reCaptcha->verifyResponse(
// $_SERVER["REMOTE_ADDR"], $_POST["g-recaptcha-response"]
// );
// }
// if ($response == null) {
// echo "<script>alert('Por favor assinale o campo de verificação!');history.back();</script>";
// exit;
// }
// Verifica a resposta do Captcha
if ($response != null && $response->success) {
$nome_site_utf8 = utf8_decode($nome_site);
$nome_contato = utf8_decode($_POST['nome_contato']);
$email_contato = $_POST['email_contato'];
$telefone_contato = $_POST['telefone_contato'];
$assunto_contato_utf8 = utf8_decode($_POST['assunto_contato']);
$mensagem_contato = utf8_decode(nl2br($_POST['mensagem_contato']));
$link_anterior = $_POST['link_anterior'];
//checando se o e-mail é válido
$email_contato = strtolower($email_contato);
$qtd_email = explode("#", $email_contato);
if (count($qtd_email) <= 1) {
//se não possuir # aparece a mensagem
echo "<script>alert('Por favor, insira um e-mail válido!');history.back();</script>";
exit;
} else if (count($qtd_email) == 2) {
$ip = gethostbyname($qtd_email[1]);
//função gethostbyname recupera o ip do domínio, se não tiver ip aparece a mensagem
if ($ip == $qtd_email[1]) {
echo "<script>alert('Por favor, insira um e-mail válido!');history.back();</script>";
exit;
}
}
if ($assunto_contato_utf8 == '') {
echo "<script>alert('Por favor, preencha um Assunto!');history.back();</script>";
exit;
}
$nome_contato = ucwords(strtolower($nome_contato));
$email_conteudo = "<html>
<body>
<font face='Arial' style='color: #606060;'>
<table border='0' style='width: 400px;>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Assunto:</b><br/> $assunto_contato_utf8<br/><br/> </td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Nome:</b><br/> $nome_contato<br/> </td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>E-mail:</b><br/> $email_contato<br/> </td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Telefone:</b><br/> $telefone_contato<br/> </td> </tr>
<tr> <td style='text-align: left; font-size: 14px; color: #606060;'> <b>Mensagem:</b><br/> $mensagem_contato<br/> </td> </tr>
<tr> <td style='height: 20px;'></td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Página de Referência:</b><br/> $link_anterior<br/> </td> </tr>
<tr> <td style='padding-top: 20px;'></td> </tr>
</table>
</font>
</body>
</html>";
/** Montagem e Envio do e-mail * */
date_default_timezone_set('Etc/UTC');
include 'phpmailer/class.phpmailer.php';
include 'phpmailer/class.smtp.php';
require 'phpmailer/PHPMailerAutoload.php';
}
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
//$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = $mail_host;
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = $mail_port;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = $mail_user;
//Password to use for SMTP authentication
$mail->Password = $mail_pass;
//Set who the message is to be sent from
$mail->setFrom("$mail_send", "$nome_contato");
//Set an alternative reply-to address
$mail->addReplyTo("$email_contato", "$nome_contato");
//Set who the message is to be sent to
$mail->addAddress("$email_formulario", "$nome_site_utf8");
$mail->addAddress("suporte#cgdw.com.br,suporte1#cgdw.com.br");
//$mail->addAddress("$email_formulario2", "$nome_site");
//Set the subject line
$mail->Subject = $assunto_contato_utf8 . " - ".$nome_site_utf8;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->Body = $email_conteudo;
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "<script>alert('Desculpe, ocorreu um erro ao enviar, tente novamente!');window.open('" . $link_encaminhar_erro . "', '_self');</script>";
exit;
} else {
echo "<script>alert('Sua mensagem foi enviada, agradecemos seu contato!');window.open('" . $link_encaminhar_concluido . "', '_self');</script>";
exit;
}
?>
i solve the problem this way :
Delete ALL de old code (that was made for someone else) and star fresh. ending up with this code that work
<?php
if (isset($_POST['enviar'])) {
require_once 'phpmailer/PHPMailerT.class.php';
$json = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=6LfEGGoUAAAAAOQQe3y9EkneINSI9bEQLYOATrfr&response=' . $_POST['g-recaptcha-response']));
if (!is_object($json) || $json->success != true) {
echo "<script>alert('Por favor assinale o campo de verificação!');history.back();</script>";
}
$nome_contato = ($_POST['nome_contato']);
$telefone_contato = ($_POST['telefone_contato']);
$email_contato = ($_POST['email_contato']);
$assunto_contato = ($_POST['assunto_contato']);
$mensagem_contato = ($_POST['mensagem_contato']);
$Content = "
<p><b>Nome:</b> " . ($nome_contato) . "</p>
<p><b>Telefone:</b> " . ($telefone_contato) . "</p>
<p><b>Email:</b> " . ($email_contato) . "</p>
<p><b>Assunto:</b> " . ($assunto_contato) . "</p>
<p><b>Mensagem:</b> " . ($mensagem_contato) . "</p>";
$PHPMailer = new PHPMailerT();
$PHPMailer->IsSMTP();
$PHPMailer->SMTPAuth = true;
$PHPMailer->SMTPDebug = 1;
$PHPMailer->SMTPSecure = '';
$PHPMailer->Port = 587;
$PHPMailer->Host = 'mail.server.com.br';
$PHPMailer->Username = 'envio#server.com.br';
$PHPMailer->Password = '';
$PHPMailer->Subject = 'Contato do Site - Intergroup';
$PHPMailer->SetFrom($email_contato, $nome_contato);
$PHPMailer->AddAddress('contato#server.com.br');
$PHPMailer->AddAddress('suporte1#cgdw.com.br');
$ContentSend = "<table width=\"600\">";
$ContentSend .= "<tr>";
$ContentSend .= "<td>$Content<td>";
$ContentSend .= "</tr>";
$ContentSend .= "</table>";
$PHPMailer->MsgHTML($ContentSend);
if ($PHPMailer->Send()) {
echo "<script>alert('Mensagem enviada com sucesso.');history.back();</script>";
} else {
$msgReturn = '<div class="msgErro">Ocorreu um erro, tente mais tarde!</div>';
}
}
echo $msgReturn;
?>

Send email using PHP Mailer

I'm trying to send emails using PHP Mailer. The site is uploaded to a free hosting. The error is displayed about failed SMTP connection. I'm hoping to someone that has expertise in this matter.
Here goes my code.
require '../extensions/phpmailer/PHPMailerAutoload.php';
$emailAddress = 'SampleEmail';
$password = 'Emailpassword';
$subject = 'Invitation to employee portal';
$message = '
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Invitation</title>
<body style ="background:#eee;">
<table cellpadding="0" cellspacing="0" border="0" id="backgroundTable" style ="padding: 40px; max-width:640px;background-color:#f3f3f3;display:block;margin:0 auto; font-family:Lato, sans-serif; color:#626262;font-size:13px;line-height:22px;" width ="600">
<tbody>
<tr>
<td style ="background-color: #3552f2; padding: 34px 122px;">
<h1 width ="600" style ="max-width:600px;width:100%; text-align:center; color:#fff;">HRMS DHVTSU</h1>
</td>
</tr>
<tr>
<td style ="background-color: #ffffff; text-align: center; padding: 40px;">
<h1 style="font-size: 40px; color:#000; font-style: italic;">Sorry your account has been deactivated.</h1>
<br>
<p style ="color:#000; font-size: 16px;">For any questions please contact HR Department.</p>
<br>
<br>
</td>
</tr>
<tr>
<td style ="background-color: #3552f2; text-align: center; font-size: 16px; color: #fff;">
<p>© 2016. All rights reserved.</p>
</td>
</tr>
</tbody>
</table>
</body>';
$mail = new PHPMailer;
$mail->isSMTP();
// $mail->SMTPDebug = 2;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = $emailAddress;
$mail->Password = $password;
$mail->setFrom('noreply#hrms.com', 'HRMS');
$mail->addReplyTo('johndoe#gmail.com', 'HRMS');
$mail->addAddress($email);
$mail->Subject = $subject;
$mail->msgHTML($message);
if (!$mail->send()) {
// $error = "Mailer Error: " . $mail->ErrorInfo;
// echo '<script>alert("'.$error.'");</script>';
return false;
}else {
$query = 'Update employee_has_credentials set status = '.self::STATUS_INACTIVE.' where id= '.$id.'';
$result = $this->con->prepare($query);
$result->execute(array($id));
if($result->rowCount()){
return true;
}else{
return false;
}
}
Possible duplicate of PHP Mailer issue use that code and it will fix your problem, because you have not added following code:
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php'
or go to above link more description you can see from that answer.

unable to generate automail on daily bases

I am unable to generate auto mail on daily bases. The issue is it is not able to generate it automatically. Where as i have a same sort of code which does generates it everyday. With all the same details. The code is exactly same except the database query.
Here is my code:
<?php
session_start();
require("../connect.php");
/* require files for MAIL */
require("class.phpmailer.php");
require("class.smtp.php");
/* require files for MAIL ENDS */
/******** Get the list of audits done in week risk category falls under High Risk and during the previous visit also the location was under High risk category ----mail on every Saturday**********/
$current_date = date('Y-m-d');
//$current_date ='2015-08-22';;
/*$start_time = time() - (6*86400);
$start_dt = date('Y-m-d',$start_time);*/
$pagent_array = array();
$query="Select * from `location_details` ld
Left Join `answer_general_qc` ans_general on ans_general.lid=ld.id
Left Join `audit_general` general on general.qtno = ans_general.qt
Left Join `audit_general_option` general_opt on general_opt.opt_id = ans_general.ans_remark
where ld.completed ='1' and ld.priority != 'qc' and general.qtno ='1' and ans_general.opt = 'no' and
STR_TO_DATE(ld.`date_audited`,'%d-%m-%Y') = '".$current_date."'";
$result=mysql_query($query);
$th_style="border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede";
$td_style="border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff";
$table_result .="<table align='center' rules='all' style='font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;' border='1';>
<thead>
<tr>
<th style='".$th_style."'>Sr No</th>
<th style='".$th_style."'>Location Code</th>
<th style='".$th_style."'>Location Name</th>
<th style='".$th_style."'>PAgent</th>
<th style='".$th_style."'>Address 1</th>
<th style='".$th_style."'>Address 2</th>
<th style='".$th_style."'>District</th>
<th style='".$th_style."'>State</th>
<th style='".$th_style."'>Priority</th>
<th style='".$th_style."'>Remark by TO</th>
<th style='".$th_style."'>Remark by TO</th>
</tr>
</thead>
<tbody>";
$sr_no=1;
if(mysql_num_rows($result) != 0)
{
while($row=mysql_fetch_array($result))
{
if($row['option_text'] == "")
{
$option_text="Other";
}
else
{
$option_text=$row['option_text'];
}
$table_result .= "
<tr>
<td style='".$td_style."'>".$sr_no."</td>
<td style='".$td_style."'>".$row['location']."</td>
<td style='".$td_style."'>".$row['agent']."</td>
<td style='".$td_style."'>".$row['pagent']."</td>
<td style='".$td_style."'>".$row['address1']."</td>
<td style='".$td_style."'>".$row['address2']."</td>
<td style='".$td_style."'>".$row['district']."</td>
<td style='".$td_style."'>".$row['state']."</td>
<td style='".$td_style."'>".$row['priority']."</td>
<td style='".$td_style."'>".$option_text."</td>
<td style='".$td_style."'>".$row['qc_remark']."</td>
</tr>";
$sr_no++;
}
}
else
{
$table_result .="<tr><td colspan='9' align='center'>No Locations Found</td></tr>";
}
$table_result .="</tbody>
</table>";
// echo $table_result; exit;
/* Code to send MAIL */
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "host";
$mail->SMTPAuth = true;
//$mail->SMTPSecure = "ssl";
$mail->Port = 25;
$mail->Username = "Username";
$mail->Password = "Password";
$mail->From = "From";
$mail->FromName = "Name";
$mail->AddAddress("Email");
$mail->AddBCC("Email CC");
$body = "Dear All,<br /><br />For the review conducted on ".date('d-m-Y',strtotime($current_date))." in the following locations we have found deviation in question 1.1 (ie Does this location exist exactly at the address provided?) <br /><br /><br /><br />";
$body .= $table_result;
$body .= "<br /><br />Warm Regards <br /><br />
Note : Please do not reply to this email as this is an automated mail generated
";
//end body
$mail->IsHTML(true);
//$mail->Subject = "Ref : RC1/HR/".strtoupper($pa)."/".date('F Y',(time()-(5*86400)));
$mail->Subject = "Ref : Lrr 1.1 deviation";
$mail->Body = $body;
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
/* Code to send MAIL Ends */
//mail($to,$subject,$message,$headers);
echo 'Mail sent to '.$pa.'<br /><br />';
/****** END of sending mail **********/
?>
If you want to send mails on a regular or daily basis the ideal way to do that would be to use cron job for sending the mails.By using cron you can specify what application do you want the cron to run on.Also you will be able to specify what time exactly do you want the mail to be sent.
Refer here https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job .
Hope it helps.

Php Error Message " Uncaught exception 'Exception' with message 'Query Failed:Array"

I tried to render a table from MS-SQL Database to Webpage and i get this error.
I'm still new in PHP. Please help
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"])
?>
Error Displayed
Warning: sqlsrv_query() expects parameter 1 to be resource, null given in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 26
Notice: Array to string conversion in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Fatal error: Uncaught exception 'Exception' with message 'Query Failed:Array' in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php:29 Stack trace: #0 C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php(8): SimpleUsers->getUsers() #1 {main} thrown in C:\Users\Adam\Desktop\SimpleUsers MSSQL\Useraccess.php on line 29
Your conn class property is not set.
Before you call $stmt = sqlsrv_query($this->conn, $sql); you must set it up in sqlsrv_connect.
Try adding construct:
public function __construct()
{
$this->conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
}
Useraccess.php
<?php
$path = dirname(__FILE__);
require_once(dirname(__FILE__)."/simpleusers/config.inc.php");
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers->getUsers();
class SimpleUsers
{
private $mysqli , $stmt;
private $conn;
private $sessionName = "SimpleUsers";
public $logged_in = false;
public $userdata;
public $uPassword;
public $salt;
public $conn=$GLOBALS["conn"] ;
public function getUsers()
{
$sql = "SELECT DISTINCT userId, uUsername, uActivity, uCreated FROM users ORDER BY uUsername ASC";
$stmt = sqlsrv_query($this->conn, $sql);
if( $stmt == false){
throw new Exception("Query Failed:".sqlsrv_errors());
}
$stmt->execute();
$stmt->store_result();
if( $stmt->num_rows == 0){
return array();
}
$users = array();
$i = 0;
while( $stmt->fetch() )
{
$users[$i]["userId"] = $userId;
$users[$i]["uUsername"] = $username;
$users[$i]["uActivity"] = $activity;
$users[$i]["uCreated"] = $created;
$i++;
}
}
}
?>
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style type="text/css">
* { margin: 0px; padding: 0px; }
body
{
padding: 30px;
font-family: Calibri, Verdana, "Sans Serif";
font-size: 12px;
}
table
{
width: 800px;
margin: 0px auto;
}
th, td
{
padding: 3px;
}
.right
{
text-align: right;
}
h1
{
color: #FF0000;
border-bottom: 2px solid #000000;
margin-bottom: 15px;
}
p { margin: 10px 0px; }
p.faded { color: #A0A0A0; }
</style>
</head>
<body>
<h1>User administration</h1>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Username</th>
<th>Last activity</th>
<th>Created</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4" class="right">
Create new user | Logout
</td>
</tr>
</tfoot>
<tbody>
<?php foreach
( $users as $user ): ?>
<tr>
<td><?php echo $user["uUsername"]; ?></td>
<td class="right"><?php echo $user["uActivity"]; ?></td>
<td class="right"><?php echo $user["uCreated"]; ?></td>
<td class="right">Delete | User info | Change password</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
config.inc.php
<?php
$GLOBALS["serverName"] = "DESKTOP-KRF6KT7\SQLEXPRESS";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "sa";
$GLOBALS["pwd"] = "twinz0000";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$GLOBALS["conn"] = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"] );
?>
Hope it will help.
I have these two items in my php.ini file enabled:
extension=php_pdo_sqlsrv_53_ts.dll
extension=php_sqlsrv_53_ts.dll
Which is what I had before. Using Wamp Server. PHP 5.3.13 all the same as before. What else am I missing that is not allowing this to connect to the SQL server.
After connection file code.
<?php
$GLOBALS["serverName"] = "localhost";
$GLOBALS["database"] = "SimpleUsers";
$GLOBALS["uid"] = "root";
$GLOBALS["pwd"] = "";
$GLOBALS["connectionInfo"] = array(
"Database"=>$GLOBALS["database"],
"UID"=>$GLOBALS["uid"],
"PWD"=>$GLOBALS["pwd"]);
$conn = sqlsrv_connect($GLOBALS["serverName"], $GLOBALS["connectionInfo"]);
?>

Categories