How do I loop through a form and post to database?

That query define 2 columns but 3 values. It looks like the order_id needs to be added as the first column if that is the proper value for $value. Furthermore, I don’t think you need to quote the order_id value because it is *probably an integer data type column. I say that because it sounds like a foreign key to what would be an auto increment primary key. Though I could be wrong. So just pointing that out.


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (order_id,block_type,block_quantity)
                      VALUES ({$value},
                   '{$_POST['100type'][$key]}',
                   '{$_POST['100quantity'][$key]}'          
                  )";
    $result = mysql_query($sql) or die('Could not insert data');
}

?> 

Also, please look into preventing SQL injection. Right now this query is susceptible to a SQL injection attack. Ideally variable binding and prepared statements should be used to prevent SQL injection. Though the standard MySQL adapter does not support that easily. If this is a single isolated script I would highly recommend looking into an adaptor that provides an interface to easily use prepared statements with variable binding. Otherwise, the values can be escaped using mysql_real_escape_string. Though using mysql_real_escape_string is not the preferred nor most absolute method to prevent SQL injection. Again, if this is a single isolated script than consider using mysqli or pdo instead of the standard mysql functions. Otherwise, look into updating the antire application to use a more modern adaptor that supports prepared statements with variable binding.

Still cannot insert data :frowning:

order_id is a foreign key. below is what i tried with all columns.
id
order_id - FK
block_type
block_quantity
block_pallets
block_extras


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (id,order_id,block_type,block_quantity,block_pallets,block_extras)
                      VALUES (null,{$value},
                    '{$_POST['100type'][$key]}',
                    '{$_POST['100quantity'][$key]}',
		    '{$_POST['100pallets'][$key]}',
		    '{$_POST['100extras'][$key]}'  				   
                  )";
    $result = mysql_query($sql) or die('Could not insert data');
}

thanks for the advice on security. I should look into it.

What I would recommend than is to print the SQL statement and run it directly in MySQL though a GUI client or the terminal.


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (id,order_id,block_type,block_quantity,block_pallets,block_extras)
                      VALUES (null,{$value},
                    '{$_POST['100type'][$key]}',
                    '{$_POST['100quantity'][$key]}',
            '{$_POST['100pallets'][$key]}',
            '{$_POST['100extras'][$key]}'                     
                  )";

echo "<p>$sql</p>"; // copy and paste this query into your MySQL client of choice and use the error to figure out what needs to be done

    $result = mysql_query($sql) or die('Could not insert data');
}

What I would recommend than is to print the SQL statement and run it directly in MySQL though a GUI client or the terminal.


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (id,order_id,block_type,block_quantity,block_pallets,block_extras)
                      VALUES (null,{$value},
                    '{$_POST['100type'][$key]}',
                    '{$_POST['100quantity'][$key]}',
            '{$_POST['100pallets'][$key]}',
            '{$_POST['100extras'][$key]}'                     
                  )";

echo "<p>$sql</p>"; // copy and paste this query into your MySQL client of choice and use the error to figure out what needs to be done

    $result = mysql_query($sql) or die('Could not insert data');
}

When a query errors or is not functioning in the way intended the best thing to do is print it out and run it directly in MySQL. That will provide a good indication as to the whether the query is malformed or the issue is application side. In some cases just printing it might reveal details like missing values that are expected to exist yet don’t.

the foreign key is causing it
#1452 - Cannot add or update a child row: a foreign key constraint fails (bots.order_details_table, CONSTRAINT order_details_table_ibfk_1 FOREIGN KEY (order_id) REFERENCES order_table (id) ON DELETE CASCADE ON UPDATE CASCADE)

how do I copy the id from the first table to the order_id in the second table? that’s the foreign key that needs to be populated. They are all in one form.
some data are inputed in one table and some in the other

That error means that there is no row in the table order_table with a column id containing the $value.

This can be confirmed by running the below query replacing the $value with the expected integer.


select count(*) ct from order_table where id = $value

A single row should be returned with a value of 0.

Once that is confirmed the solution is to reference a row that does exist or create the row in that table.

It is good though that you are using a foreign key. Otherwise, you would essentially have an orphaned row in the order details table.

#1054 - Unknown column ‘$value’ in ‘where clause’

$value is meant to a token/placeholder for the actual value of the order_id. Go back to the printed query and copy the value of the order_id column that would be inserted.

when I run this: SELECT COUNT(*) ct FROM order_table WHERE id = 1
it works with no error

the id should be 1 right? first record. and that value should be entered into the foreign key

how do I access the id of the first table in order to insert its value into the foreign key?


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (id,order_id,block_type,block_quantity,block_pallets,block_extras)".
                      "VALUES (null,{$value},". // <- you want the value of the $value variable
                    "'{$_POST['100type'][$key]}',
                    '{$_POST['100quantity'][$key]}',
            '{$_POST['100pallets'][$key]}',
            '{$_POST['100extras'][$key]}'"                    
                  )";

echo "<p>$sql</p>"; // copy and paste this query into your MySQL client of choice and use the error to figure out what needs to be done

    $result = mysql_query($sql) or die('Could not insert data');
}  

that is : 10.01
which is the type… ie. {$_POST[‘100type’]

so $value has the same value as the $_POST[‘100type’]
that shouldn’t be like that right?


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (order_id,block_type,block_quantity,block_pallets,block_extras)
                      VALUES ({$value},'{$_POST['100type'][$key]}'
                    '{$_POST['100quantity'][$key]}',
            '{$_POST['100pallets'][$key]}',
            '{$_POST['100extras'][$key]}'                     
                  )";

this does foreach($_POST[‘100type’] AS $key=>$value) , where 100type as $key should not be the key right? The foreign key should be the key??? but it is not in the POST data

but it should be like that foreach($_POST[‘100type’] AS $key=>$value) cause there are more tables on the same page with different types. right?

there is the 100type, the 150type, 200type so on. all going into the same table

mysql_insert_id() :- Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
you may retain this id to insert into your order_id column.

Here is the code:


<?php
include('db.php'); //connect

//print_r($_POST);

	echo '<pre style="text-align: left;">' . print_r($_POST, true) . '</pre>';
	echo '------------------------------------------------<br/>';
	
$insert="INSERT INTO order_table (id, company_name, delivery_address, order_date, delivery_date, status, hb_checked, loaded_by, pallets, extra_blocks, extra_pallets, total_pallets)
VALUES
(NULL,'$_POST[companyname]','$_POST[deliveryaddress]','$_POST[orderdate]','$_POST[deliverydate]','$_POST[status]','$_POST[checked]','$_POST[loadedby]','$_POST[sumpallets]','$_POST[sumextras]','$_POST[makeup]','$_POST[grandtotal]')";

$kavli = mysql_insert_id();
$kavli = intval($kavli);
echo $kavli;

echo "<p>$insert</p>";


foreach($_POST['100type'] AS $key=>$value) {
    $sql = "INSERT INTO order_details_table
           (id, order_id,block_type,block_quantity,block_pallets,block_extras)
			VALUES (NULL,'$kavli','{$_POST['100type'][$key]}','{$_POST['100quantity'][$key]}','{$_POST['100pallets'][$key]}','{$_POST['100extras'][$key]}')";

echo "<p>$sql</p>"; // copy and paste this query into your MySQL client of choice and use the error to figure out what needs to be done

    $result = mysql_query($sql) or die('Could not insert data');
}

?>

And my result:


Array
(
    [companyname] => NACA
    [deliveryaddress] => Stuart Park
    [orderdate] => 2013-04-20
    [deliverydate] => 2013-05-22
    [status] => Completed
    [checked] => Yes
    [loadedby] => Me
    [sumpallets] => 4
    [sumextras] => 130
    [makeup] => 1
    [grandtotal] => 5
    [submit] => Submit Order
    [100type] => Array
        (
            [1] => 10.01
            [2] => 10.02
            [3] => 10.03
            [4] => 10.04
            [5] => 10.31
            [6] => 10.83
            [7] => 10.702
            [8] => 10.772
            [9] => 10.71
            [10] => 10.72
            [11] => 10.73
            [12] => 10.74
        )

    [100perpallet] => Array
        (
            [1] => 180
            [2] => 240
            [3] => 360
            [4] => 576
            [5] => 144
            [6] => 288
            [7] => 280
            [8] => 560
            [9] => 360
            [10] => 480
            [11] => 720
            [12] => 1152
        )

    [100quantity] => Array
        (
            [1] => 654
            [2] => 256
            [3] => 0
            [4] => 0
            [5] => 0
            [6] => 0
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
        )

    [100pallets] => Array
        (
            [1] => 3
            [2] => 1
            [3] => 0
            [4] => 0
            [5] => 0
            [6] => 0
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
        )

    [100extras] => Array
        (
            [1] => 114
            [2] => 16
            [3] => 0
            [4] => 0
            [5] => 0
            [6] => 0
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 0
        )

)
------------------------------------------------
0
INSERT INTO order_table (id, company_name, delivery_address, order_date, delivery_date, status, hb_checked, loaded_by, pallets, extra_blocks, extra_pallets, total_pallets) VALUES (NULL,'NACA','Stuart Park','2013-04-20','2013-05-22','Completed','Yes','Me','4','130','1','5')

INSERT INTO order_details_table (id, order_id,block_type,block_quantity,block_pallets,block_extras) VALUES (NULL,'0','10.01','654','3','114')

Could not insert data

My sql statement gives me this error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (bots.order_details_table, CONSTRAINT order_details_table_ibfk_1 FOREIGN KEY (order_id) REFERENCES order_table (id) ON DELETE CASCADE ON UPDATE CASCADE)

when creating the relationship, how should I setup UPDATE and DELETE options?

OK I’m not going to create a relationship.

I could just get the last id from the order_table, and hardcode insert it into the order_id column of the order_details_table

How do I get the last id of a table??? tried a few google searches with no luck :frowning:

GOT IT :slight_smile:

<?php
include(‘db.php’); //connect

echo '&lt;pre style="text-align: left;"&gt;' . print_r($_POST, true) . '&lt;/pre&gt;';

mysql_query(“INSERT INTO order_table (company_name, delivery_address, order_date, delivery_date, status, hb_checked, loaded_by, pallets, extra_blocks, extra_pallets, total_pallets)
VALUES
(‘$_POST[companyname]’,‘$_POST[deliveryaddress]’,‘$_POST[orderdate]’,‘$_POST[deliverydate]’,‘$_POST[status]’,‘$_POST[checked]’,‘$_POST[loadedby]’,‘$_POST[sumpallets]’,‘$_POST[sumextras]’,‘$_POST[makeup]’,‘$_POST[grandtotal]’)”);

$currentid = mysql_insert_id();

foreach($_POST[‘100type’] AS $key=>$value) {
$sql = “INSERT INTO order_details_table
(order_id, block_type, block_quantity, block_pallets, block_extras)
VALUES (‘$currentid’, ‘{$_POST[‘100type’][$key]}’,‘{$_POST[‘100quantity’][$key]}’,‘{$_POST[‘100pallets’][$key]}’,‘{$_POST[‘100extras’][$key]}’)”;

$result = mysql_query($sql) or die('Could not insert data');

}

?>

that is the spirit of learning.

:slight_smile:

thanks for all the help