Solved

How can i post a php foreach loop in my database.

Posted on 2016-10-19
13
81 Views
Last Modified: 2016-10-26
This is my cart function.
As you can see my function creates a foreach loop for my products.
And i used a hidden inputs to hold values because td tags does not post anything.
full-ui.png
this is where i get all the values to post in DB.
include_once '../incluedes/conn_cms.php';//session started here 
		
 if(isset($_GET['submit_post'])){

			$date = date('Y-m-d');
		 	$fabric=$_GET['fabric'];
		 	$size=$_GET['size'];
		 	
		 	$desenho=$_GET['desenho'];
		 	$numero=$_GET['numero'];
		 	$vari=$_GET['vari'];

		 	$qnty=$_GET['qnty'];
		 	$cost=$_GET['cost'];
		 	$subT=$_GET['subtotal'];


		 	$pedido=$date." ".$_SESSION['userName']."-".$_SESSION['userLName'];

			 $query = "SELECT * FROM almofadas WHERE id_price='$fabric'";
		   	 $result = mysqli_query($conn,$query);
		   	 while($rows = mysqli_fetch_assoc($result)){
		    	$tecido=$rows['tecido'];
		   	}

		 	$ins_sql = "INSERT INTO orders (fabric,size,product_quantity,order_id,product_img,product_title,variante,product_cost,product_subtotal) 
                     VALUES ('$tecido', '$size' , '$qnty', '$pedido', '$desenho', '$numero', '$vari', '$cost', '$subT')";
		 	if ($conn->query($ins_sql) === TRUE) {
				echo "New record created successfully";
				} else {
				echo "Error: " ;
				}
			$conn->close();
			 }

Open in new window


But the problem is when i post in my database it only gets the first product in my cart.
I need to post each products in my DB.
How i will do that?

This is my form ...

<form action="postOrder.php" method="GET" enctype="multipart/form-data" class="form-horizontal">

      <div class="container">
        <div class="row">
          
          <table class="table table-striped table-hover" id="myTable">
            <thead>
            <h4></h4>
              <tr>
              <th>Image</th>
              <th>Produto</th>
              <th>Fabric</th>
              <th>Size</th>
              <th>Qntd</th>
              <th>Cost</th>
              <th>sub.total</th>
              </tr>
            </thead>
            <tbody >
             
              
          <?php cart(); ?>
            
          
            </tbody>
          </table>
          <div class="form-group">
                <input name="submit_post" class="first" type="submit" >
             </div>
          </form>

Open in new window


In my footer i have a button where it triggers a hidden submit button.
full ui
this is my script to trigger the hidden submit button.

jQuery("input.second").click(function(){
   jQuery("input.first").trigger('click');
   return false;
});

Open in new window

0
Comment
Question by:James Allan
  • 5
  • 4
  • 2
  • +1
13 Comments
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 41850398
Some comments on your code
1. Your While statement does not have a closing }
2. Look at this code
<option value="'.$t50.'" name="'.$t50.'">50x'.$t50.'</option>

Open in new window

<options> don't have a name attribute
3. You appear to be looping through your products creating the table but using the same names each time around (see below)
4. You are using $_GET - not a good idea - there is a limit on the length of a URL (GET) - which could become problematic if you have a lot of products you are moving. It also means your submission is not safe if you submit twice - you can end up adding product twice
5. You are not santizing your form variables - trusting that
a) they are present
b) They contain valid data
Is a security watchit

You should consider making your form variables arrays
<select name="size[]">

Open in new window

Instead of
<select name="size">

Open in new window

That way when you do
$size = isset($_POST['size']) ? $_POST['size'] : array();

Open in new window

$size will be an array of sizes
$size[0] will be the size for product 1
$size[1] will be the size for product 2
etc
Example
Look at this example to see what is in the $_POST using arrays as form variables
http://www.marcorpsa.com/ee/t1737.html
1
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41850416
This expert suggested creating a Gigs project.
There are several issues here, and you might want to consider posting this in E-E Gigs, where you can get a professional to help you.  I can't follow all of it, but I can see some things in the PHP script that cry out for remediation :-)
<?php
include_once '../incluedes/conn_cms.php';//session started here 

// YOU MUST NOT USE A GET-METHOD REQUEST TO UPDATE A DATABASE
 if(isset($_GET['submit_post'])){

            $date = date('Y-m-d');
            $fabric=$_GET['fabric'];
            $size=$_GET['size'];
            
            $desenho=$_GET['desenho'];
            $numero=$_GET['numero'];
            $vari=$_GET['vari'];

            $qnty=$_GET['qnty'];
            $cost=$_GET['cost'];
            $subT=$_GET['subtotal'];


            $pedido=$date." ".$_SESSION['userName']."-".$_SESSION['userLName'];

             // YOU MUST NOT USE EXTERNAL DATA IN A QUERY STRING - IT MUST BE ESCAPED
             $query = "SELECT * FROM almofadas WHERE id_price='$fabric'";
             
             $result = mysqli_query($conn,$query);
             
             // YOU MUST NOT USE $result UNTIL YOU HAVE TESTED FOR SUCCESS
             while($rows = mysqli_fetch_assoc($result)){
                
                // EACH ITERATION THROUGH THE WHILE LOOP OVERWRITES THE VALUE IN $tecido
                $tecido=$rows['tecido'];
            }

            // YOU MUST NOT USE EXTERNAL DATA IN A QUERY STRING - IT MUST BE ESCAPED
            $ins_sql = "INSERT INTO orders (fabric,size,product_quantity,order_id,product_img,product_title,variante,product_cost,product_subtotal) 
                     VALUES ('$tecido', '$size' , '$qnty', '$pedido', '$desenho', '$numero', '$vari', '$cost', '$subT')";
            if ($conn->query($ins_sql) === TRUE) {
                echo "New record created successfully";
                } else {
                
                // YOU MIGHT WANT TO LOG ERROR INFORMATION, SO IT CAN BE USED TO FIX THE ERROR
                echo "Error: " ;
                }
            $conn->close();
             }

Open in new window

0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41850851
Ray and Julian have already pointed out some fundamental flaws in your code which you'll need to address.

Your friend here is something called a Prepared Statement. It will allow you to create one INSERT query and then loop through your data executing that query. A neat trick to help you loop through your data is to name your form fields using an array syntax - Julian has already alluded to this, but to take it a step further, take a look at this naming convention:

product[1][size]
product[1][desenho]
product[1][numero]
...
product[2][size]
product[2][desenho]
product[2][numero]

You can then loop through your products, one by one, inserting them into the database by executing your query. Here's a very brief overview:

if(isset($_POST['submit_post']))
{
    $stmt = $conn->prepare("INSERT INTO orders (size, desenho, numero) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $size, $desenho, $numero);

    foreach ($_POST['product'] as $key => $product) {
        extract($product);
        $stmt->execute();
    }
}

Open in new window


As long as you get the form fields named correctly, and match them to the bind_param call, you can make your life a lot easier :)
2
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 1

Author Comment

by:James Allan
ID: 41851394
look how i did
<?php  
include_once '../incluedes/conn_cms.php'; 
			if(isset($_POST['submit_post']))
		{
			$date = date('Y-m-d');
			$size = isset($_POST['size']) ? $_POST['size'] : array();
			$numero = isset($_POST['numero']) ? $_POST['numero'] : array();
			$vari = isset($_POST['vari']) ? $_POST['vari'] : array();
			$desenho = isset($_POST['desenho']) ? $_POST['desenho'] : array();
			$fabric = isset($_POST['fabric']) ? $_POST['fabric'] : array();
			$size = isset($_POST['size']) ? $_POST['size'] : array();
			$qnty = isset($_POST['qnty']) ? $_POST['qnty'] : array();
			$cost = isset($_POST['cost']) ? $_POST['cost']: array();
			$subtotal = isset($_POST['subtotal']) ? $_POST['subtotal'] : array();
			$total = isset($_POST['total']) ? $_POST['total'] : array();
			$all_products = isset($_POST['all_products']) ? $_POST['all_products'] : array();

			$pedido=$date." ".$_SESSION['userName']."-".$_SESSION['userLName'];

			 $query = "SELECT * FROM almofadas WHERE id_price='$fabric'";
		   	 $result = mysqli_query($conn,$query);
		   	 while($rows = mysqli_fetch_assoc($result)){
		    	$tecido=$rows['tecido'];
		    	$fabric=$tecido;
		   	}

		   	
		    $stmt = $conn->prepare("INSERT INTO orders (fabric,size,product_quantity,order_id,product_img,product_title,variante,product_cost,product_subtotal) 
		    VALUES ('$fabric', '$size' , '$qnty', '$pedido', '$desenho', '$numero', '$vari', '$cost')");
		    $stmt->bind_param($fabric, $size , $qnty, $pedido, $desenho, $numero, $vari, $cost);

		    foreach ($_POST['product'] as $key => $product) {
		    	
		        extract($product);
		        $stmt->execute();
		    }

		}

Open in new window

i get these errors (the lines match code above)

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 20

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Notice: Array to string conversion in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 29

Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\xampp\htdocs\system\clientes\gallery\postOrder.php:30 Stack trace: #0 {main} thrown in C:\xampp\htdocs\system\clientes\gallery\postOrder.php on line 30
0
 
LVL 54

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41851469
$fabric = isset($_POST['fabric']) ? $_POST['fabric'] : array();

Open in new window

$fabric is an array which means
$query = "SELECT * FROM almofadas WHERE id_price='$fabric'";

Open in new window

Is going to try and use
Array (
  0 => 'Fabric1'.
  1  => 'Fabric2'
   ...
)

Open in new window


As a string.

I don't think from your implementation you have understood the advice given in the previous posts.

Recommendation

Build yourself a small little test form.
Hard code your different product options onto the form - assume a client who wants to buy a lot of different things and many of them.

Point your form at this script
<?php
 header('Access-Control-Allow-Origin: *');  

echo "POST\n";
echo "<pre>" . print_r($_POST, true) . "</pre>";
echo "GET\n";
echo "<pre>" . print_r($_GET, true) . "</pre>";
if ($_FILES) {
echo "<pre>" . print_r($_FILES, true) . "</pre>";

  echo "FILES\n";
  echo <<< TABLE
  <table class="table">
    <tr>
      <th>ID</th><th>Name</th><th>Type</th><th>Size</th>
TABLE;
  foreach($_FILES as $id => $file) {
	if (is_array($file)) {
		foreach($file['name'] as $k => $f) {
		echo <<< ROW
    <tr>
      <td>{$id}[{$k}]</td><td>{$f}</td><td>{$file['type'][$k]}</td><td>{$file['size'][$k]}</td>
    </tr>

ROW;
		}
	}
	else {
		echo <<< ROW
    <tr>
      <td>{$id}</td><td>{$file['name']}</td><td>{$file['type']}</td><td>{$file['size']}</td>
    </tr>

ROW;
		unlink($file['tmp_name']);
	}
  }
}
echo <<< TABLE
  </table>
TABLE;

echo file_get_contents('php://input');

Open in new window


Examine the output from posting to that script.
Play with different options on your test form looking at the data that is returned until you are familiar with it. Then post back here with questions and / or go back to your original script and implement.
1
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 41851596
You seem to have mixed 2 different ideas into your solutions - part of Julians and part of mine. Have a read through both, and choose 1, and then try and implement that.

As Julian said, create a small, static, sample page and work with that until you understand what's going on.
1
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41851912
Please consider stepping back from the "big problems" and getting a foundation in how HTML, CSS, JavaScript, PHP, and MySQL work together.  It's a bit of a journey to get from where you are to where you want to be, but all of us have made that journey and now the work is easier for us, because we had an extended period of structured learning.
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
1
 
LVL 1

Author Comment

by:James Allan
ID: 41853508
Based on julian advice,now its working.
The problem is that my hidden inputs values only contains the right value when i refresh the page.

$date = date('Y-m-d');
$size = isset($_POST['size']) ? $_POST['size'] :  array();
$numero = isset($_POST['numero']) ? $_POST['numero'] :  array();
$vari = isset($_POST['vari']) ? $_POST['vari'] :  array();
$desenho = isset($_POST['desenho']) ? $_POST['desenho'] :  array();
$fabrics= isset($_POST['fabric']) ? $_POST['fabric'] :  array();
$size = isset($_POST['size']) ? $_POST['size'] :  array();
$qnty = isset($_POST['qnty']) ? $_POST['qnty'] :  array();
$cost = isset($_POST['cost']) ? $_POST['cost']:  array();
$subtotal = isset($_POST['subtotal']) ? $_POST['subtotal'] :  array();
$total = isset($_POST['total']) ? $_POST['total'] :  array();
$all_products = isset($_POST['all_products']) ? $_POST['all_products'] :  array();
			

$pedido=$date." ".$_SESSION['userName']."-".$_SESSION['userLName'];

		foreach ($fabrics as $fabric)
	 {
               $index = array_search($fabric, $fabrics);

		$query = "SELECT * FROM almofadas WHERE id_price='$fabrics[$index]'";
		$result = mysqli_query($conn,$query);
		while($rows = mysqli_fetch_assoc($result)){
		$tecido=$rows['tecido']; 
	}


$ins_sql = "INSERT INTO orders (fabric,size,product_quantity,order_id,product_img,product_title,variante,product_cost,product_subtotal) 
VALUES ('$tecido', '$size[$index]' , '$qnty[$index]', '$pedido', '$desenho[$index]', '$numero[$index]', '$vari[$index]', '$cost[$index]', '$subtotal[$index]')";
			 	   
	 if ($conn->query($ins_sql) === TRUE) {
	 echo "New record created successfully";
	 } else {
	 echo "Error: " ;
	}
				
}

		   	$conn->close();

Open in new window

0
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 41853517
Again basic understanding of how the process works is required.

First question - what function are your hidden inputs serving? With the right AJAX implementation you don't need them.
0
 
LVL 1

Author Comment

by:James Allan
ID: 41853530
I am using the php post method and my <td> tags with names[] does not post anything, so i used hidden inputs to hold some data, because inputs works on the post method.
So as you said Julian if i use ajax to post, i won't need the hidden inputs because ajax can get the values from my <td> tags correct?
0
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 41853551
my <td> tags with names[]
I don't understand

so i used hidden inputs to hold some data,
What data?

because ajax can get the values from my <td> tags correct?
AJAX is a means for communicating with the server - it is a bit of a misnomer as it standards for Asynchronous Javascript and XML - we don't use XML much mostly JSON so should probably be named AJAJ?.
Anyway, in this case AJAX does not do anything per se. You can use JavaScript / jQuery to retrieve any html / value from the document and having done so you can use AJAX to send that information to the server.

But that is beside the point - I am trying to understand why you are storing values in <td> elements at all?
0
 
LVL 1

Author Comment

by:James Allan
ID: 41853562
I'm sorry,  i didn't post the code i was referring to.

<td name="qnty[]" class="product'.$id.' " value="'.$value.'">'.$value.'</td>

Open in new window


 <input  type="hidden" name="qnty[]" value="'.$value.'"/> 

Open in new window


Here you can see that my name="qnty[]" is in my td tag.(php does not grab this value)


But when i use input the values are sent,but not updated,the only things that updates onclick or onchange in my <td> tags.
0
 
LVL 54

Assisted Solution

by:Julian Hansen
Julian Hansen earned 500 total points
ID: 41853578
Why not
echo <<< ROW
<td class="product{$id}">
  <input type="text" name="qnty[]" value="{$value}" />
</td>
ROW;

Open in new window

i.e. put the value in the <td> - you can't do it the way you were doing it.

The right way is to use the input controls and style them to look the way you want.
1

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses four methods for overlaying images in a container on a web page
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question