1

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 .= '<a href="http://www.example.com/"><img src="http://cdn.example.com/static/images/emailhead.jpg" alt="MY Site" /></a>';
$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 = '[email protected]';                   // 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('[email protected]', 'YAQOOB');  // Add a recipient
$mail->addAddress('[email protected]');               // 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();  
?>
14
  • 3
    How are you getting the $cid like of variable outside the loop Commented Apr 8, 2015 at 10:47
  • From a hidden Input within $_POST Commented Apr 8, 2015 at 10:51
  • 1
    But within your code I can't figure it out. If I'm wrong please correct me. Commented Apr 8, 2015 at 10:56
  • 1
    $cid, $cname, $cphone and other variables in foreach has different value in each step through the loop and you use those variables ONCE after the loop, thats wrong, isnt it?...I think you have to do all the rest with message IN this foreach; not outside it...If i am wrong, correct me :) Commented Apr 8, 2015 at 10:58
  • 1
    @yaqoob you are assigining $cid like of variable within loop not outside loop check it yourself and correct me if I am wrong. Commented Apr 8, 2015 at 11:05

2 Answers 2

2

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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Comments are not for extended discussion; this conversation has been moved to chat.
1

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>';
   }
}

7 Comments

is there a way to do that after the foreach loop?
@yaqoob why after? what are you trying to do?
Your $cid,$pcode,$pname and other variables are changing in every step in foreach, so you should do this in foreach I think...Or you could store all values of variables to array and process it later, but I think this solution is better
@UserProg in the foreach loop there's alot of stuff going on, like SQL quiries (Inserting) and all. It will complicate the code i just want the $message part separate. is that possible?
@yaqoob yes it is. You have to store the variable in an array and then continue processing it outside. Refer answer by Sanjay below
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.