Avatar of James Allan
James Allan
 asked on

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

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

PHPjQueryAJAX

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Julian Hansen

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
Ray Paseur

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

Chris Stanyon

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 :)
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
James Allan

ASKER
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
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Chris Stanyon

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.
Ray Paseur

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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
James Allan

ASKER
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

Julian Hansen

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.
James Allan

ASKER
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?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Julian Hansen

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?
James Allan

ASKER
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.
SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.