PHPMail sending email right away - php

While I'm just trying to pull up data from the db, as soon as the page shows up with the data it is already sending an email. How can I prevent it from sending the email right away. What I want to happen is I retrieved data from the db > shows it to a page > edit the page > update the db and send an email. This is the only point where I want an email to be sent out.
Here is my entire EDITED CODE as per suggestion,
$update = filter_input_array(INPUT_POST, $update_args);
$date = filter_input_array(INPUT_POST, $date_args);
$result = NULL;
$colcomments = NULL;
$dsn = 'mysql:dbname='.DBname.';host='.DBhost.';port=';
try {
$conn = new PDO($dsn, DBuser, DBpswd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['submit'])) {
if(!isset($_SESSION['update'])) {
$_SESSION['update'] = true;
//retrieve values from database
if($date['from'] !== NULL && $date['to'] !== NULL){
// get table data
$sql = 'SELECT `id`, `changeid`,
FROM `tracker` WHERE `scheduled_start_date` BETWEEN :d1 AND :d2';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':d1', $date['from'], PDO::PARAM_STR);
$stmt->bindParam(':d2', $date['to'], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}else {
unset($_SESSION['update']);
//put your mail function here
function two_dim_array_to_html_table($arr){
$ret = "<table border='1' width='auto' cellpadding='1px' cellspacing='0px' align='center'>\n";
$ret .= "\t<tr>\n";
foreach($arr[0] as $key => $val){
$ret .= "\t\t<th>".$colcomments[$key]."</th>\n";
}
$ret .= "\t</tr>\n";
foreach($arr as $row){
$ret .= "\t<tr>\n";
foreach($row as $column){
$ret .= "\t\t<td>".$column."</td>\n";
}
$ret .= "\t</tr>\n";
}
$ret .= "<table>\n";
return $ret;
}
if($result) {
$Body = "<html>\n"
. "<head>\n"
. "</head>\n"
. "<body>\n"
. two_dim_array_to_html_table($result, $colcomments)
. "</body>\n"
. "</html>\n";
//Setting up Mail
$mail = new PHPMailer();
if (EMAIL_USE_SMTP) {
// Set mailer to use SMTP
$mail->IsSMTP();
//useful for debugging, shows full SMTP errors
//$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
// Enable SMTP authentication
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
// Enable encryption, usually SSL/TLS
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
// Specify host server
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
} else {
$mail->IsMail();
}
$mail->From = EMAIL_FROM_ADDRESS;
$mail->FromName = EMAIL_FROM_NAME;
$mail->AddAddress('test.test#domain.COM');
$mail->Subject = 'Daily Tasks - "'.date('d-m-Y').'"';
$mail->WordWrap = 100;
$mail->IsHTML(true);
$mail->Body = $Body;
$mail->Send();
}
//update database records
if(isset($update['id']) && is_array($update['id']) && !empty($update['id'])){
$sql = "UPDATE `tracker`
SET `changeid` = :bv_changeid
WHERE `id` = :bv_id ";
if($stmt = $conn->prepare($sql)){
$stmt->bindParam(':bv_changeid', $changeid, PDO::PARAM_INT);
$stmt->bindParam(':bv_id', $id, PDO::PARAM_INT);
$updateRowCount = 0;
// update multiple rows - all of selected in form
foreach($update['id'] as $key => $val){
$changeid = $update['changeid'][$val];
$id = $val;
$stmt->execute();
$updateRowCount += $stmt->rowCount();
}
if($updateRowCount > 0){
$message['info'][] = "Updated ".$updateRowCount." row/s";
}
else {
$message['warning'][] = "Tracker db not updated.";
}
}
else {
$message['error'][] = "Prepare error!!!";
}
}
}
}else {
//show the normal calender/form
if(is_array($result)){
echo '
<fieldset>
<legend>Assign</legend>
<div>Changes will affect updated rows only.</div>
<p></p>
<table width=auto cellpadding=1px cellspacing=0px border=1 align=center id=assign>
<thead>
<tr>';
// column comment from DB as column header
foreach($result[0] as $key => $val){
echo '<th align=center>'.$colcomments[$key].'</th>';
}
echo '
</tr>
</thead>
<tbody>';
foreach($result as $row => $info){
echo '<tr>';
foreach($info as $key => $val){
if($key=='id'){
echo '<td title="'.$colcomments[$key].'">'.$val.'.<input type="hidden" name="'.$key.'['.$info['id'].']" value="'.$val.'" id="rowid_'.$val.'" /></td>';
}
else {
echo '<td title="'.$colcomments[$key].'"><input type="text" name="'.$key.'['.$info['id'].']" value="'.$val.'" /></td>';
}
}
echo '</tr>';
}
echo '
</tbody>
</table>
</fieldset>';
}
}
}
Here is the entire code for the Submit button,
<html>
<head>
<title>Ticket Assignment</title>
</head>
<body class="oneColFixCtrHdr">
<script>
</script>
<div id="mainContent">
<?php
foreach($message as $key => $val){
// show error, warning and info messages
if(!empty($val)){
echo '<div style="margin:4px;background:'.$bgcol[$key].';border:2px solid grey;border-radius:8px;">';
foreach($val as $item){
echo '<div style="margin:8px;">'.$item.'</div>';
}
echo '</div>';
}
}
?>
<div>
<form action="assign_test1.php" method="post">
<fieldset>
<legend>Select Date</legend>
<div>Select Date from and Date to</div>
<p></p>
<input type="date" name="from" id="from" value="<?=$date['from']; ?>" />
<input type="date" name="to" id="to" value="<?=$date['to']; ?>" />
<div><input type="submit" name="submit" id="submit" value="Submit"/></div>
</fieldset>
</form>
</div>
</div>
</body>
</html>

The code you provided doesn't have everything so I will explain how it should work
if(isset($_POST['submit'])) {
if(!isset($_SESSION['update'])) {
$_SESSION['update'] = true;
//retrieve values from database
}else {
unset($_SESSION['update']);
//put your mail function here
//update database records
}
}else {
//show the normal calender/form
}
I hope this helps you.
If you need anything else, please let me know. I am here to help. Good luck!

Related

Attach Database Backup file in E-Mail send not working

I am using following code to take backup of my mysql database.
With this code, a file is created and get saved in same folder where this script is kept. It is working perfectly.
I am trying to email this file using phpmailer. But I am stucked as no file is getting attached to receiving email. (email is delivered without attached file...)
Basic code is taken from https://write.corbpie.com/php-pdo-mysql-backup-script-with-compression-option/
Help is appreciated... and thank you in advanced...
Backup creating code part is as follows :
<?php
include_once("../../include/mysqli_constants.php");
require("../../PHPMailer/class.phpmailer.php");
$db_server = constant('HST');
$db_name = constant('DBN');
$db_user = constant('USR');
$db_pass = constant('PWD');
$site_url = constant('FILEROOT');
$from_email = constant('FROMEMAIL');
$from_name = constant('FROMNAME');
$mail_to1 = 'mypersonal#gmail.com';
$mail_to1_name = 'Dr Manish Joshi';
$mail_to2 = '';
$mail_to2_name = '';
$save_dir = './';
$file_name_prefix = 'my_website_';
$date = strtolower(date('d_F_Y_H_i_s_A'));
/* Do NOT EDIT BELOW */
$backup_config = array(
'DB_HOST' => $db_server,////Database hostname
'DB_NAME' => $db_name,//Database name to backup
'DB_USERNAME' => $db_user,//Database account username
'DB_PASSWORD' => $db_pass,//Database account password
'INCLUDE_DROP_TABLE' => false,//Include DROP TABLE IF EXISTS
'SAVE_DIR' => '',//Folder to save file in
'SAVE_AS' => $file_name_prefix,//Prepend filename
'APPEND_DATE_FORMAT' => 'Y_m_d_H_i_s',//Append date to file name
'TIMEZONE' => 'Asia/Kolkata',//Timezone for date format
'COMPRESS' => true,//Compress into gz otherwise keep as .sql
);
echo backupDB($backup_config);
Email sending part is as follows :
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Host = constant('EMAILHOST');
$mail->AddAddress(''.$mail_to1.'', ''.$mail_to1_name.'');
$mail->IsSMTP();
$mail->SMTPAuth = constant('SMTPAuth');
$mail->SMTPSecure = 'tls';
$mail->Mailer = "smtp";
$mail->SMTPDebug = constant('SMTPDEBUG');
$mail->Username = constant('SMTPUSERNAME');
$mail->Password = constant('SMTPPASSWORD');
$mail->Port = 587;
$mail->From = constant('FROMEMAIL');
$mail->FromName = constant('FROMNAME');
$mail->WordWrap = 50;
$mail->Subject = '['.$from_name.'] Cron Backup MySQL On - ' . $date;
$mail->Body = $save_string.' File is attached via cron';
$mail->AddAttachment($save_string);
if (!$mail->AddAttachment($save_string)) {
echo 'Erreur : ' . $mail->ErrorInfo . "\n";
$mail->Body .= "\n" . 'Erreur : ' . $mail->ErrorInfo;
}
if (!$mail->Send()){
echo 'Message could not be sent. <p>';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Function to create database backup is as follows and it is working OK and creating db backup and saving file in folder.
/* FUNCTION Starts */
function backupDB(array $config): string {
$db = new PDO("mysql:host={$config['DB_HOST']};dbname={$config['DB_NAME']}; charset=utf8", $config['DB_USERNAME'], $config['DB_PASSWORD']);
$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
date_default_timezone_set($config['TIMEZONE']);
$do_compress = $config['COMPRESS'];
if ($do_compress) {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql.gz';
$zp = gzopen($save_string, "a9");
} else {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql';
$handle = fopen($save_string, 'a+');
}
//array of all database field types which just take numbers
$numtypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'real');
$return = "";
$return .= "CREATE DATABASE `{$config['DB_NAME']}`;\n";
$return .= "USE `{$config['DB_NAME']}`;\n";
//get all tables
$pstm1 = $db->query('SHOW TABLES');
while ($row = $pstm1->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
//cycle through the table(s)
foreach ($tables as $table) {
$result = $db->query("SELECT * FROM $table");
$num_fields = $result->columnCount();
$num_rows = $result->rowCount();
if ($config['INCLUDE_DROP_TABLE']) {
$return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
}
//table structure
$pstm2 = $db->query("SHOW CREATE TABLE $table");
$row2 = $pstm2->fetch(PDO::FETCH_NUM);
$ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]);
$return .= "\n\n" . $ifnotexists . ";\n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
//insert values
if ($num_rows) {
$return = 'INSERT INTO `' . $table . '` (';
$pstm3 = $db->query("SHOW COLUMNS FROM $table");
$count = 0;
$type = array();
while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) {
if (stripos($rows[1], '(')) {
$type[$table][] = stristr($rows[1], '(', true);
} else {
$type[$table][] = $rows[1];
}
$return .= "`" . $rows[0] . "`";
$count++;
if ($count < ($pstm3->rowCount())) {
$return .= ", ";
}
}
$return .= ")" . ' VALUES';
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$counter = 0;
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$return = "\n\t(";
for ($j = 0; $j < $num_fields; $j++) {
if (isset($row[$j])) {
//if number, take away "". else leave as string
if ((in_array($type[$table][$j], $numtypes)) && (!empty($row[$j]))) {
$return .= $row[$j];
} else {
$return .= $db->quote($row[$j]);
}
} else {
$return .= 'NULL';
}
if ($j < ($num_fields - 1)) {
$return .= ',';
}
}
$counter++;
if ($counter < ($result->rowCount())) {
$return .= "),";
} else {
$return .= ");";
}
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$return = "\n\n-- ------------------------------------------------ \n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$error1 = $pstm2->errorInfo();
$error2 = $pstm3->errorInfo();
$error3 = $result->errorInfo();
echo $error1[2];
echo $error2[2];
echo $error3[2];
if ($do_compress) {
gzclose($zp);
} else {
fclose($handle);
}
return "{$config['DB_NAME']} saved as $save_string";
}
?>
I have edited this code and now it is working...
Edited code kept on github...
https://github.com/vaidyamanishjoshi/db-backup-with-pdo-and-email-it

PHPMailer sending multiple email cc address separated by coma symbol

I have problem sending multiple email cc separated by coma symbol using PHPMailer . . i'm using PHP 7.
I have these data in my mysql database contains multiple email address in single user account separated by coma (,) .
I already follow the answer from this question here, but its not working. email can only be sent to john#mail.com . billy#mail.com did not receive any mail.
I tried to echo var_dump(maildbs);
output shown without coma . .
john#mail.combilly#mail.com
Here's my PHP code . .
sendmail.php
<?php
$connect = mysqli_connect("", "", "", "");
global $connect;
if(isset($_POST['Submit'])){
$staffname = $_POST['staffname'];
$sql = "SELECT * FROM table WHERE staff_name ='$staffname'";
$get = mysqli_query($connect,$sql);
if($get && mysqli_num_rows($get) > 0 )
{
while($row = mysqli_fetch_assoc($get))
{
$maildbs = explode(',',$row["email_address"]);
foreach($maildbs as $maildb){
date_default_timezone_set('Etc/UTC');
require_once '../PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "host";
$mail->Port = 25;
$mail->SMTPAuth = false;
$mail->setFrom('sender#mail.com', 'Sender');
$mail->addAddress('mail#mail.com','receipent');
$mail->addCC($maildb);
$mail->Subject = 'PHPMailer SMTP without auth test';
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
$mail->AltBody = 'This is a plain-text message body';
$mail->Body = 'body content';
$mail->addAttachment('images/phpmailer_mini.png');
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
}
mysqli_free_result($get);
}
}
?>
<!DOCTYPE html>
<html><title>Test Email</title></head>
<body>
<table>
<form action="sendmail.php" method="POST">
<tr>
<td>Staff Name :</td>
<td><input type="text" name="staffname" value="" ></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="send email"></td>
</tr>
</form>
</table>
</body>
</html>
Appreciate if someone can help.
use explode php function
$email = explode(',', $toEmail);
for ($i = 0; $i < count($email); $i++) {
$mail->addAddress($email[$i], 'recipient ');
}
if ($ccEmail != null) {
$emailCC = explode(',', $ccEmail);
for ($i = 0; $i < count($emailCC); $i++) {
$mail->addCC($emailCC[$i]);
}
}
if ($ccBCC != null) {
$emailBCC = explode(',', $ccBCC);
for ($i = 0; $i < count($emailBCC); $i++) {
$mail->addBCC($emailBCC[$i]);
}
}

Looping variable after another loop

i'm trying to loop a variable whose data populates from another loop of array's
HERE is the loop
for ($i=0; $i < $cid; $i++){
$message .= '<tr>
<td>'.$pcode.'</td>
<td>'.$pname.'</td>
<td>'.$pprice.'</td>
<td>'.$pqty.'</td>
</tr>';
}
And the variables in <td></td> are generated from this loop
foreach($_POST['item_cid'] as $key => $value) {
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
}
I don't know how to make this loop work, I got no errors on submit,
am i looping it correctly?
The Updated Code:
<?php
session_start();
require('admin/connect.php');
require('includes/phpmailer/PHPMailerAutoload.php');
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$resultArr = array();
$i = 0;
foreach($_POST['item_cid'] as $key => $value) {
//Data for Orders Table
$cid = intval(mysqli_real_escape_string($connection,$value));
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
//SOLUTION FROM SANJAY
$resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
$i++;
//Data for Customers Table
$cname = mysqli_real_escape_string($connection,$_POST['item_cname'][$key]);
$cemail = mysqli_real_escape_string($connection,$_POST['item_cemail'][$key]);
$cphone = mysqli_real_escape_string($connection,$_POST['item_cphone'][$key]);
$caddress = mysqli_real_escape_string($connection,$_POST['item_caddress'][$key]);
$ctotal = mysqli_real_escape_string($connection,$_POST['item_ctotal'][$key]);
//$sql = "INSERT INTO orders (cid, ordprod_code, ordprod_name, ordprod_price, ordprod_qty) VALUES ('$value', '$pcode', '$pname', '$pprice', '$pqty')";
//$sql2 = "INSERT INTO customers (cid, cname, cemail, cphone, caddress, ctotal) VALUES ('$value','$cname','$cemail','$cphone','$caddress','$ctotal')";
if ($connection->query($sql) === TRUE) {
echo "Orders record created successfully \n";
}
// } else {
// echo "Error: " . $sql . "<br>" . $connection->error;
// }
if ($connection->query($sql2) === TRUE) {
echo "Customers record created successfully \n";
}
// } else {
// echo "Error: " . $sql2 . "<br>" . $connection->error;
} // close the loop
print_r($resultArr);
//********************************
// START EMAIL FUNCTION
//********************************
$message = '<html><body>';
$message .= '<img src="http://cdn.example.com/static/images/emailhead.jpg" alt="MY Site" />';
$message .= '<h3>Customer Information:</h3>';
$message .= '<table rules="all" border="1" style="border-color: #ccc;" cellpadding="10">';
$message .= '<tr><td><strong>CustomerID</strong></td><td>'. $cid .'</td></tr>';
$message .= '<tr><td><strong>Name:</strong></td><td>'. $cname .'</td></tr>';
$message .= '<tr><td><strong>Email:</strong></td><td>'. $cemail .'</td></tr>';
$message .= '<tr><td><strong>Phone:</strong></td><td>'. $cphone .'</td></tr>';
$message .= '<tr><td><strong>Address:</strong></td><td>'. $caddress .'</td></tr>';
$message .= '</table>';
$message .= '<br />';
$message .= '<h3>Order Details:</h3>';
$message .= '<table rules="all" border="1" style="border-color: #ccc;" cellpadding="10">';
$message .= '<tr style="background:#eee;">
<td><strong>Product Code</strong></td>
<td><strong>Product Name</strong></td>
<td><strong>Product Price</strong></td>
<td><strong>Product Qty</strong></td>
</tr>';
// SOLUTION FROM SANJAY
$i = 0;
for ($i=0; $i < ((isset($resultArr[$i]['cid']) && count($resultArr[$i]['cid']) > 0 ) ?$resultArr[$i]['cid'] : 0); $i++)
{
$message .= '<tr>
<td>'.$resultArr[$i]['pcode'].'</td>
<td>'.$resultArr[$i]['pname'].'</td>
<td>'.$resultArr[$i]['pprice'].'</td>
<td>'.$resultArr[$i]['pqty'].'</td>
</tr>';
}
$message .= '<tr style="background:#eee;">
<td colspan="2">Total Amount</td>
<td>'.$ctotal.'</td>
<td></td>
</tr>';
$message .= '</table>';
$message .= '</body></html>';
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
if (preg_match($pattern, $cemail)) {
$cleanedFrom = $cemail;
} else {
return "The email address you entered was invalid. Please try again!";
}
//***************************************
// SEND MAIL USING GMAIL SMTP SERVER
//***************************************
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->Port = 587; //Set the SMTP port number - 587 for authenticated TLS
$mail->setFrom(''.$cemail.'', ''.$cname.''); //Set who the message is to be sent from
$mail->addReplyTo(''.$cemail.'', ''.$cname.''); //Set an alternative reply-to address
$mail->addAddress('owner#example.com', 'YAQOOB'); // Add a recipient
$mail->addAddress('owner#example.com'); // Name is optional
$mail->addCC('');
$mail->addBCC('');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->addAttachment('/user/file.doc'); // Add attachments
$mail->addAttachment('/images/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New order arrived from CustomerID #'.$cid.'';
$mail->Body = ''.$message.'';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
} // Data Inserted & Emailed Close IF Statement
session_destroy();
?>
Try this:
$message = "";
$resultArr = array();
$i = 0;
foreach($_POST['item_cid'] as $key => $value)
{
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
$resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
$i++;
}
$i = 0;
for ($i=0; $i < (isset($resultArr[$i]['cid']) && $resultArr[$i]['cid'] ?$resultArr[$i]['cid'] : 0); $i++)
{
$message .= '<tr>
<td>'.$resultArr[$i]['pcode'].'</td>
<td>'.$resultArr[$i]['pname'].'</td>
<td>'.$resultArr[$i]['pprice'].'</td>
<td>'.$resultArr[$i]['pqty'].'</td>
</tr>';
}
What about something like this?
$message = "";
foreach($_POST['item_cid'] as $key => $value)
{
$cid = mysqli_real_escape_string($connection,$value);
$pcode = mysqli_real_escape_string($connection,$_POST['item_code'][$key]);
$pname = mysqli_real_escape_string($connection,$_POST['item_name'][$key]);
$pprice = mysqli_real_escape_string($connection,$_POST['item_price'][$key]);
$pqty = mysqli_real_escape_string($connection,$_POST['item_qty'][$key]);
for ($i=0; $i < $cid; $i++)
{
$message .= '<tr>
<td>'.$pcode.'</td>
<td>'.$pname.'</td>
<td>'.$pprice.'</td>
<td>'.$pqty.'</td>
</tr>';
}
}

while($row = mysql_fetch_row($result))

I'm trying to get a php to pull all records from a mysql db, and display them formatted. For some reason the 1st record displays correctly, but the 2nd record that displays directly below it does not show the field name. What am I doing wrong?
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '***';
$database = 'db';
$table = 'upstable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}"); // sending query
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
while($row = mysql_fetch_row($result)) // printing table rows
{
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[0]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[1]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[2]v</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[3]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[4]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[5]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[6]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[7]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</div></b><div id='column2'>$row[8]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[9]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[10]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[11]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[12]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[13]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[14]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[15]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[16]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[17]</div><br><br><br>";
$row = 0;
}
mysql_free_result($result);
?>
UPDATED:
ALMOST fixed, but it's not quite right. It is making each complete set of data alternating backgrounds (the class "column2" is grey and "columnn" is white), rather than every other row in each set. Does that make more sense?
This is what I'm using right now, what should I change?
$row_num = 0;
$css_classes[0] = 'column2';
$css_classes[1] = 'column';
while($row = mysql_fetch_assoc($result))
{
$row_num++;
$class = $css_classes[$row_num % 2];
foreach ($row as $col_name => $col_val)
{
echo "<div class='$class'><b>{$col_name}:</b></div><div class='$class'>$col_val</div><br>";
}
echo "<br><br>";
Below code should work perfectly, and has more readibility.
while($row = mysql_fetch_assoc($result))
{
foreach ($row as $col_name => $col_val)
{
echo "<div id='column2'><b>{$col_name}:</b></div><div id='column2'>$col_val</div><br>";
}
}
Updated
Well, I'm not good at HTML/CSS. I would like to to like this if I were you.
$row_num = 0;
$css_classes[0] = 'gray_style';
$css_classes[1] = 'white_style';
while($row = mysql_fetch_assoc($result))
{
$row_num++;
$class = $css_classes[$row_num % 2];
foreach ($row as $col_name => $col_val)
{
echo "<div id='column2' class='$class'><b>{$col_name}:</b></div><div id='column2'>$col_val</div><br>";
}
}
You're only fetching the first row(because $results default position is [0], which is the first row.).
you obviously don't understand the process involved in fetching sorting, and displaying data with php, but here's an example of a prepared statement and a normal query using mysqli.
mysqli query
function getmarkets()
{
global $mysqli;
$query = $mysqli->query("SELECT pair, last_price FROM all_currency_data");
$num_rows = $query->num_rows;
if($num_rows > 0) {
while($row = $query->fetch_assoc())
{
$mkt = explode("-",$row["pair"]);
$coin = $mkt[0];
$base = $mkt[1];
echo '<a class="animate" href="?p=trade&market='.urlencode($row["pair"]).'" style="text-decoration: none;"><li class="mkt-normal" id="'.$row["pair"].'_div">'.$coin.'/'.$base.' <span class="price" id="'.$row["pair"].'_price">'.$row["last_price"].'</span></li></a>';
}
$query->close();
}
}
prepared statement
$stmt = $mysqli->prepare("SELECT user,message,timestamp FROM uc_support_replies WHERE tickethash = ? ORDER BY timestamp ASC");
$stmt->bind_param('s',$ticket);
$stmt->execute();
$stmt->bind_result($user,$message,$timestamp);
while($stmt->fetch())
{
if(in_array($user, $admins)) {
$color = '0404B4';
}else{
$color = '2E2E2E';
}
$output .=
'
<div class="msgdiv">
<hr class="five">
<span class="user_name" style="color:#'.$color.'"><u>'.$user.'</u></span>
</br>
<span class="user_message">'.$message.'</span>
</br>
<span data-livestamp="'.$timestamp.'">'.$timestamp.'</span>
<hr class="five">
</div>
';
}
The MySQL extension was officially deprecated since PHP 5.5.0 in late 2012 and it will be removed in the future. Recommended alternative since PHP 5 and later is MySQLi ("i" stands for "improved"). http://www.php.net/manual/en/book.mysqli.php

How do I output my data in a threaded way based on parent ID?

I have a forum that students are posting in. If the student responds to the main post, the postId is set to 0. If a student replies to another student's post, the postId is set to the replyId of the student's original post.
I am trying to write some PHP that will essentially create a new table for each post, with the exception of if a postid is set to a reply Id, then create a new row in that table.
I have the SQL laid out in SQLFiddle which can be found here:
http://sqlfiddle.com/#!2/611e2d/5
Using this example, what I'm looking for is replyid one to be put in a new html table, with response ID 3 in a new row underneath that. Then with ReplyId 2, would create a new html table.
This is just a basic threaded forum view of responses.
Thank you!
[code]
$i = 0;
$aR = 0;
$currentPost = '';
if(mysql_num_rows($getResponses) > 0)
{
while($respData = mysql_fetch_array($getResponses))
{
if(($respData['postId'] != $currentPost))
{
if($i!=0)
{
echo '</table><br /><br />';
}
echo '<table width = "875px" cellspacing = "0" cellpadding = "0" border = "0">';
$i=0;
}
$currentPost = $respData['postId'];
$color_A = 'class="altRow1"';
$color_B = 'class="altRow2"';
$altRowColor = ($aR % 2) ? $color_A : $color_B;
$studentName = getStudents($respData['userId']);
$studentName = explode(" ", $studentName);
$studentFirstName = $studentName[0];
echo '<tr ' . $altRowColor . '>
<td align="center" width = "225px" class="forumTopic"><img src="images/'.getStudentPics($respData['userId']).'.png" /><br />Posted By ' . getStudents($respData['userId']) . '<br />on '.date("m/d/Y h:i a", strtotime($respData['responseDate'])) . '</td>
<td width = "650px" class="forumTopic">' . $respData['replyText'] . '</td>
</tr>
<tr ' . $altRowColor . '>
<td class="forumTopic" colspan = "2" align="center"><span class="topicLinkStyle">Reply to '.$studentFirstName .'</span></td>
</tr>';
$i++;
$aR++;
}
echo '</table><br /><br />';
}
Here is a very simple example you can then make your own CSS to format the HTML anyway you want you can even use that link I posted on your comment as example.
The buildTree will order the replies properly in a tree manner for easy later usage and the printTree will print it recursively.
<?php
// Your database info
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';
if (!isset($_GET['topic_id']))
{
die('No topic id was given.');
}
$con = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT replyId,
topicId,
postId,
replyText,
responseDate,
userId
FROM forumResponses
WHERE topicId = ?
ORDER BY replyId";
$result = $con->prepare($sql);
$result->bindParam(1, $_GET['topic_id'], PDO::PARAM_INT);
$result->execute();
if ($result->rowCount() == 0)
{
die('No messages found...');
}
$threads = array();
while($row = $result->fetchALL(PDO::FETCH_ASSOC))
{
$threads = $row;
}
$data = buildTree($threads);
$con = NULL;
function buildTree($ar, $pid = NULL) {
$op = array();
foreach($ar as $item)
{
if($item['postId'] == $pid)
{
$op[$item['replyId']] = array(
'replyText' => $item['replyText'],
'userId' => $item['userId'],
'responseDate' => $item['responseDate'],
'parentId' => $item['postId']
);
// using recursion
$children = buildTree($ar, $item['replyId']);
if($children)
{
$op[$item['replyId']]['children'] = $children;
}
}
}
return $op;
}
function printTree($ar)
{
foreach ($ar as $reply)
{
?>
<li>
<div>
<header>userId <?php echo $reply['userId']; ?> - <?php echo $reply['responseDate']; ?></header>
<?php echo $reply['replyText']; ?>
</div>
<?php
if (isset($reply['children']) && count($reply['children']) > 0)
{
echo " <ul>\n";
printTree($reply['children']);
echo " </ul>\n";
}
echo " </li>\n";
}
}
?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Threaded Comments Block</title>
</head>
<body>
<div>
<h1>Reading Topic <?php echo $_GET['topic_id']; ?></h1>
<div>
<ul>
<?php
printTree($data);
?>
</ul>
</div>
</div>
</body>
</html>
NOTE: The above code is merely to show you an example of how store the result in a threaded manner as well as to print it, you will have to make your own out of this example.
I think it will be better to reconstruct the table for that..hmm here is my suggestion
Table Post (suggested main table for responses of a topic)
Fields:
postId, topicId(topic where this post belongs), responseId(this will be the postId of the post if this post is a reply, set to 0 if main post),

Categories