I have the following html submit form. This form is a PHP_SELF and stores the input data as an array in $_POST.
<html>
<body>
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Direct Bill Information:</legend>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" />
</fieldset>
<input type="submit" value="submit" name="submit" />
</form>
</body>
</html>
I have a MySQL table that has the fields 'db_num' and 'db_amnt', and I want to insert all the input data in the array into the table. I've looked around and 'implode' seems to be the best way, but after much research I still can't get it to work. The entire PHP executes and finishes without error, however, instead of displaying all 10 rows of both columns, it just displays 2 rows of the two columns with values = 0 for all entries. This is the code I'm using:
$sql2 = array();
foreach($_POST as key=>$value)
{
if(key != 'submit')
{
if($value != '')
{
$sql2[] = '("'.mysql_real_escape_string($value['db_num']).'", "'.$value['db_amnt'].'")';
}
}
}
mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',', $sql2));
I did a little debugging and echoed the $value in the foreach loop, and it turns out that it's only displaying three terms; 'Array', 'Array', and 'submit'. Further checks showed that the only way I can get the values from the submit form to show is if I do a foreach loop through $_POST[db_num] and $_POST[db_amnt] instead of just $_POST. I'm not really sure why it's doing this and how to fix it. This is my first code in PHP and I'm learning as I go. I really appreciate any help that I can get!
try this
$db_num = $_POST['db_num'];
$db_amnt = $_POST['db_amnt'];
$items = array_combine($db_num,$db_amnt);
$pairs = array();
foreach($items as $key=>$value){
$pairs[] = '('.intval($key).','.intval($value).')';
}
mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',',$pairs));