简体   繁体   中英

If array values greater than 1 gets error

i have run a loop of array, which throws error if the array's data greater than 1 otherwise it works fine. can you please point the mistake?

HERE's THE 1st LOOP

This loop stores the data into array $resultArr

$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]);

    $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]);

}

HERE's THE 2nd LOOP

This loop prints the array data from $resultArr

for ($i=0; $i < ((isset($resultArr[$i]['cid']))); $i++) {
        $message .= '<tr>
         <td>' . $resultArr[$i]['pcode'] . '</td>
         <td>' . $resultArr[$i]['pname'] . '</td>
         <td>' . $resultArr[$i]['pprice'] . '</td>
         <td>' . $resultArr[$i]['pqty'] . '</td>
         </tr>';
 }

Please note:

This works fine until the $resultArr has only 1 record otherwise gets the errors/notices.

Notice: Undefined offset: 1 in C:\\wamp\\www\\abc\\process.php on line 26

Notice: Undefined offset: 1 in C:\\wamp\\www\\abc\\process.php on line 27

Notice: Undefined offset: 1 in C:\\wamp\\www\\abc\\process.php on line 28

Notice: Undefined offset: 1 in C:\\wamp\\www\\abc\\process.php on line 29

Notice: Undefined offset: 1 in C:\\wamp\\www\\abc\\process.php on line 30

All of these lines are pointing towards the variables defined after the $resultArr

UPDATE:

Added the HTML FORM

//hidden inputs holds the data from DB (they're never empty)
<input type="hidden" name="item_cid[]" value="78286" />
<input type="hidden" name="item_code[]" value="LS-986" />
<input type="hidden" name="item_name[]" value="Product Title" />
<input type="hidden" name="item_price[]" value="8999" />
<input type="hidden" name="item_qty[]" value="1" />

//Data submitted by user (this one also has the data, i'll make sure of it)
<input class="input-text" type="text" name="item_cname[]" placeholder="Your Name" />
<input type="text" name="item_cemail[]"  placeholder="Your Email Address"/>
<input type="text" name="item_cphone[]"  placeholder="Your Phone Number"/>
<textarea name="item_caddress[]"  placeholder="Your Address" class="input-text" rows="2" cols="2" maxlength="140"></textarea>
<input type="hidden" name="item_ctotal[]"  value="18389"/>

var_dump($_POST);

array (size=12)
  'item_cid' => 
    array (size=2)
      0 => string '78286' (length=5)
      1 => string '78286' (length=5)
  'item_code' => 
    array (size=2)
      0 => string 'LS-986' (length=6)
      1 => string 'SL-055' (length=6)
  'item_name' => 
    array (size=2)
      0 => string 'Bridal Set' (length=10)
      1 => string 'Silver Locket set  (Pendant + Earrings)' (length=39)
  'item_price' => 
    array (size=2)
      0 => string '8999' (length=4)
      1 => string '9390' (length=4)
  'item_qty' => 
    array (size=2)
      0 => string '1' (length=1)
      1 => string '1' (length=1)
  'item_timestamp' => 
    array (size=2)
      0 => string '09-04-2015 02:58:59' (length=19)
      1 => string '09-04-2015 02:58:59' (length=19)
  'item_cname' => 
    array (size=1)
      0 => string 'John Doe' (length=8)
  'item_cemail' => 
    array (size=1)
      0 => string 'john@doe.com' (length=12)
  'item_cphone' => 
    array (size=1)
      0 => string '+165798735678' (length=13)
  'item_caddress' => 
    array (size=1)
      0 => string 'Xyz Street, Area, State, Country.' (length=33)
  'item_ctotal' => 
    array (size=1)
      0 => string '18389' (length=5)
  'submit' => string 'Submit' (length=6)

print_r($resultArr);

Array ( [0] => Array ( [cid] => 78286 [pcode] => LS-986 [pname] => Bridal Set [pprice] => 8999 [pqty] => 1 ) [1] => Array ( [cid] => 78286 [pcode] => SL-055 [pname] => Silver Locket set (Pendant + Earrings) [pprice] => 9390 [pqty] => 1 ) )

THE PHP CODE OF FORM

<?php

    $rnum = mt_rand(10000,99999);
    $dt = new DateTime();
    $current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

    if(isset($_SESSION["products"]))
    {
        $total = 0;
        $cart_items = 0;

        echo '<form method="post" action="'.$site_url.'/process.php">'. "\xA";
        echo '<ul>'. "\xA";
        echo '<table>'. "\xA";

        echo '<thead>'. "\xA";
        echo '<tr>'. "\xA";

        echo '<th>'. "\xA";
        echo 'Product Code';
        echo '</th>'. "\xA";

        echo '<th>'. "\xA";
        echo 'Product Name';        
        echo '</th>'. "\xA";

        echo '<th>'. "\xA";
        echo 'Price';       
        echo '</th>'. "\xA";

        echo '<th>'. "\xA";
        echo 'Quantity';        
        echo '</th>'. "\xA";

        echo '<th>'. "\xA";
        echo '';        
        echo '</th>'. "\xA";

        echo '</tr>'. "\xA";
        echo '</thead>'. "\xA";     

        foreach ($_SESSION["products"] as $cart_itm)
        {
           $product_code = $cart_itm["code"];
           $results = $connection->query("SELECT * FROM products WHERE prod_code='$product_code' LIMIT 1");
           $obj = $results->fetch_object();
        echo '<tr>'. "\xA";

        echo '<td>'. "\xA";
        echo ''.$product_code.''. "\xA";
        echo '</td>'. "\xA";

        echo '<td>'. "\xA";
        echo ''.$obj->prod_name.''. "\xA";
        echo '</td>'. "\xA";

        echo '<td>'. "\xA";
        echo ''.number_format($obj->prod_price,0).''. "\xA";
        echo '</td>'. "\xA";

        echo '<td>'. "\xA";
        echo ''.$cart_itm["qty"].''. "\xA";
        echo '</td>'. "\xA";

        echo '<td class="product-remove">'. "\xA";
        echo '<span class="remove-itm"><a href="'.$site_url.'/cart_update.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'" class="remove" title="Remove this product from cart"> &times;</a></span>'. "\xA";
        echo '</td>'. "\xA";
        echo '</tr>'. "\xA";        

        $subtotal       = ($obj->prod_price * $cart_itm["qty"]); //Multiply item quantity * price
        $total          = ($total + $subtotal); //Add up to total price

        echo '<input type="hidden" name="item_cid[]" value="'.$rnum.'" />'. "\xA";
        echo '<input type="hidden" name="item_code[]" value="'.$product_code.'" />'. "\xA";
        echo '<input type="hidden" name="item_name[]" value="'.$obj->prod_name.'" />'. "\xA";
        echo '<input type="hidden" name="item_price[]" value="'.$obj->prod_price.'" />'. "\xA";
        echo '<input type="hidden" name="item_qty[]" value="'.$cart_itm["qty"].'" />'. "\xA";
        echo '<input type="hidden" name="item_timestamp[]" value="'.$dt->format('d-m-Y H:i:s').'" />';
        $cart_items ++;

        }

        echo '<tr id="scrtop">'. "\xA";
        echo '<td colspan="2">'. "\xA";
        echo 'Total Amount:'. "\xA";        
        echo '</td>'. "\xA";        

        echo '<td>'. "\xA";
        echo '<strong>Rs. '.number_format($total,0).' /=</strong>'. "\xA";
        echo '</td>'. "\xA";        
        echo '</tr>'. "\xA";
        echo '</table>'. "\xA";
        echo '<div class="clear"></div>'. "\xA";

        echo '<a class="order-button">Place Order</a>'. "\xA";

        echo '<div id="order-form">'. "\xA";
        echo '<h3>Place Your Order</h3>'. "\xA";
        echo '<p>Please provide your billing/shipping details to proceed.</p>'."\xA";

        echo '<p class="form-row">
        <label class="" for="item_cname[]">Your Name <span class="required">*</span></lable>
        <input class="input-text" type="text" name="item_cname[]" placeholder="Your Name" />
        </p>'."\xA";

        echo '<p class="form-row">
        <label class="" for="item_cemail[]">Email Address <span class="required">*</span></lable>
        <input type="text" name="item_cemail[]"  placeholder="Your Email Address"/>
        </p>'."\xA";

        echo '<p class="form-row">
        <label class="" for="item_cphone[]">Phone Number <span class="required">*</span></lable>
        <input type="text" name="item_cphone[]"  placeholder="Your Phone Number"/>
        </p>'."\xA";

        echo '<p class="form-row">
        <label class="" for="item_caddress[]">Address <span class="required">*</span></lable>
        <textarea name="item_caddress[]"  placeholder="Your Address" class="input-text" rows="2" cols="2" maxlength="140"></textarea>
        </p>'."\xA";

        echo '<input type="hidden" name="item_ctotal[]"  value="'.$total.'"/>'."\xA";

        echo '<input type="submit" class="button" name="submit" value="Submit" />'."\xA";
        echo '</div>'."\xA";

        echo '</form>'. "\xA";

    }else{
        echo '<h4>Your Cart is empty</h4>';
        echo '<a href="index.php">Continue Shopping</a>';
    }

    ?>

THE PHP CODE TO PROCESS THE FORM

<?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]);

    $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')";

    mysqli_query($connection,$sql);
    mysqli_query($connection,$sql2);

} // close the loop

    print_r($resultArr);
    var_dump($resultArr);
    echo ''.count($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>';
for ($i = 0; $i < count($resultArr); $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 = 'me@gmail.com';                   // SMTP username
$mail->Password = 'password';               // 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('me@gmail.com', 'YAQOOB');  // Add a recipient
$mail->addAddress('me@gmail.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();

?>

You shouldn't use array notation for the shipping details, because there's just one shipping address for the whole order. So change the form to:

    echo '<p>Please provide your billing/shipping details to proceed.</p>'."\xA";

    echo '<p class="form-row">
    <label class="" for="item_cname">Your Name <span class="required">*</span></lable>
    <input class="input-text" type="text" name="item_cname" placeholder="Your Name" />
    </p>'."\xA";

    echo '<p class="form-row">
    <label class="" for="item_cemail">Email Address <span class="required">*</span></lable>
    <input type="text" name="item_cemail"  placeholder="Your Email Address"/>
    </p>'."\xA";

    echo '<p class="form-row">
    <label class="" for="item_cphone">Phone Number <span class="required">*</span></lable>
    <input type="text" name="item_cphone"  placeholder="Your Phone Number"/>
    </p>'."\xA";

    echo '<p class="form-row">
    <label class="" for="item_caddress">Address <span class="required">*</span></lable>
    <textarea name="item_caddress"  placeholder="Your Address" class="input-text" rows="2" cols="2" maxlength="140"></textarea>
    </p>'."\xA";

    echo '<input type="hidden" name="item_ctotal"  value="'.$total.'"/>'."\xA";

And change the processing code to insert the customer information just once, not in the loop.

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]);

    $resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
    $i++;

    $sql = "INSERT INTO orders (cid, ordprod_code, ordprod_name, ordprod_price, ordprod_qty) VALUES ('$value', '$pcode', '$pname', '$pprice', '$pqty')";

    mysqli_query($connection,$sql);

} // close the loop

//Data for Customers Table
$cname = mysqli_real_escape_string($connection,$_POST['item_cname']);
$cemail = mysqli_real_escape_string($connection,$_POST['item_cemail']);
$cphone = mysqli_real_escape_string($connection,$_POST['item_cphone']);
$caddress = mysqli_real_escape_string($connection,$_POST['item_caddress']);
$ctotal = mysqli_real_escape_string($connection,$_POST['item_ctotal']);

$sql2 = "INSERT INTO customers (cid, cname, cemail, cphone, caddress, ctotal) VALUES ('$value','$cname','$cemail','$cphone','$caddress','$ctotal')";
mysqli_query($connection,$sql2);

From what i understand is that, correct me if i'm wrong, you have a set of values that repeat eg: item_code , item_name , item_price , item_qty . So you have looped through them in the first loop. But does the fields like item_cname , item_cemail , item_cphone , item_caddress , item_ctotal also repeat like the above. If no, that is your problem. You tried to get the value of item_cname inside the loop like $_POST['item_cname'][$key] .

If these values does'nt repeat or have only one value then i suggest change your code like this

$cname  = $_POST['item_cname'];
$cemail = $_POST['item_cemail'];
$cphone = $_POST['item_cphone'];
$caddress= $_POST['item_caddress'];
$ctotal = $_POST['item_ctotal'];

foreach($_POST['item_cid'] as $key => $value) {
    $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]);

    $resultArr[$i] = array('cid' => $cid, 'pcode' => $pcode, 'pname' => $pname, 'pprice' => $pprice, 'pqty' => $pqty);
    $i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM