Write loop sql query from data array (php, mysql) - php

I have a problem with php script.
I have an array, which is generated from form, where $_POST['store'] is an array from jQuery form with functionality to add multiple rows:
Array
(
[client] =>
[darvad] =>
[owca] =>
[ldrive] =>
[store] => Array
(
[product] => Array
(
[0] => 430
[1] => 440
[2] => 430
)
[quantity] => Array
(
[0] => 123
[1] => 1223
[2] => 232
)
[segums] => Array
(
[0] => Mixed park
[1] => Light vehicle
[2] => Trucks
)
[deadline] => Array
(
[0] => 2015-08-04
[1] =>
[2] =>
)
[renewal] => Array
(
[0] => 1
)
)
)
And i need to get values from this array into sql insert statment and loop it.
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline)
VALUES (...),(...),(...)....
";
HTML CODE:
<div id="container">
<div id="content" role="main">
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post" id=multiForm>
<label for="client">Klients: *</label><input id="client" type="text" name="client" placeholder="Reg.nr | Pk.kods" value="" /></br>
<label for="selector1">Darījuma vadītājs: *</label>
<select id="selector1" name="darvad" >
<option value="">-Dar. vadītājs-</option>
<?php
$sql = "SELECT Vards_Uzvards, Tables_ID FROM users";
$results = $wpdb->get_results($sql); // return an object, not ARRAY_N
if ($results) {
foreach ($results as $row) {
echo "<option value = '".$row->Tables_ID."'>".$row->Vards_Uzvards."</option>";
}}
echo "</select></br>";
?>
<label for="owcafind">Meklēt OWCA kodu: *</label><input id="owcafind" type="text" name="owca" placeholder="OWCA Kods (8)" value="" /></br>
<label for="ldrive">Mape L diskā:</label><input id="ldrive" type="text" name="ldrive" placeholder="Mape L diskā" value="" /></br>
Produkti: <img src="<?php echo site_url('/img/plus-icon.png'); ?>" width="15px"><br/>
<table class="multi">
<!-- table title -->
<tr><th>Produkts</th><th>Vienību skaits</th><th>Riska segums:</th><th>Deadline:</th><th>Atjaunojums</th><th>[Option]</th></tr>
<!-- row template, when added new row -->
<tr style="display:none;" class="templateRow">
<td><select name="store[product][]">
<option value="" selected="selected">-Produkts-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
</select></td>
<td><input type="text" name="store[quantity][]" /></td>
<td><select name="store[segums][]">
<option value="" selected="selected">-Riska segums-</option>
<option value="Mixed park">Mixed park</option>
<option value="Light vehicle">Light vehicle</option>
<option value="Trucks">Trucks</option>
<option value="Buss">Buss</option>
</select></td>
<td><input type="date" name="store[deadline][]" class="datepicker" /></td>
<td><input type="checkbox" name="store[renewal][]" value="1" /></td>
<td><a class="del" href="#"><img src="<?php echo site_url('img/minus-icon.jpg'); ?>" width="15px"></a></td>
</tr>
<!-- default values -->
<tr>
<td><select name="store[product][]" >
<option value="" selected="selected">-Produkts-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
</select></td>
<td><input type="text" name="store[quantity][]" /></td>
<td><select name="store[segums][]">
<option value="" selected="selected">-Riska segums-</option>
<option value="Mixed park">Mixed park</option>
<option value="Light vehicle">Light vehicle</option>
<option value="Trucks">Trucks</option>
<option value="Buss">Buss</option>
</select></td>
<td><input type="date" name="store[deadline][]" class="datepicker" /></td>
<td><input type="checkbox" name="store[renewal][]" value="1" /></td>
<td></td>
</tr>
<!-- /default values -->
</table>

From your question, it looks like this is what you're after
$itemCount = sizeof($array['store']['product']);
for ($i = 0; $i < $itemCount; $i++) {
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline) VALUES ("' . $array['store']['product'][$i] . '", "' . $array['store']['quantity'][$i] . '", "' . $array['store']['segums'][$i] . '", "' . $array['store']['deadline'][$i] . '");";
// Run the sql statement on the database here
}
You'll need to ensure that all user-supplied values are properly escaped before storing in the database.

If Array is called $array, then you can access the arrays values like so;
// product;
$array['store']['product'];
// quantity;
$array['store']['quantity'];
// etc.
Then, if they are to go into a single column (which is bad form and I don't recommend, then you can do something like this;
// product;
$prod_string = '';
foreach ($array['store']['product'] as $key => $prod) {
$prod_string .= $prod;
}
Then you can use $prod_string in your query.
OR, if you need to insert a row for EACH of the keys;
// We use the key from the product loop to get the others;
foreach ($array['store']['product'] as $key => $prod) {
$prod_val = $prod;
$qty_val = !empty($array['store']['quantity'][$key]) ? $array['store']['quantity'][$key] : '';
$seg_val = !empty($array['store']['segums'][$key]) ? $array['store']['segums'][$key] : '';
$dl_val = !empty($array['store']['deadline'][$key]) ? $array['store']['deadline'][$key] : '';
// Right here create your query and insert.
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline) VALUES ($prod_val, $qty_val, $seg_val, $dl_val);"
// I'm not sure what library you're using for your db management, so will leave that out.
}
Then you'll have the value of each.
NOTE - I have not checked for clean post values. Ie, sanitized input. Thats outside the scope of this question.

Have done it:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// We use the key from the product loop to get the others;
$array = $_POST;
$itemCount = sizeof($array['store']['product']);
// Loop through all $itemCount
$values_string = '';
for ($i = 0; $i < $itemCount; $i++) {
$prod = esc_sql($array['store']['product'][$i]);
$quant = esc_sql($array['store']['quantity'][$i]);
$seg = esc_sql($array['store']['segums'][$i]);
$deadline = esc_sql($array['store']['deadline'][$i]);
$renewal = esc_sql($array['store']['renewal'][$i]);
if ($i < $itemCount - 1) {
$new_str = "('".$prod."','".$quant."','".$seg."','".$deadline."','".$renewal."'),";
} else{
$new_str = "('".$prod."','".$quant."','".$seg."','".$deadline."','".$renewal."');";
}
$values_string .= $new_str;
}
// Run the sql statement on the database here
$sql_rec = "INSERT INTO tsales_funnel_mrecord (Product_type, Vien_skaits, Riska_segums, Deadline, Atjaunojums) VALUES $values_string";
$wpdb->query($sql_rec);
}

Related

How to save multiple values from same input names

How would I save in multiple rows values from same input names.
For example, my php,html code from is:
<form action="functions.php" method="post" name="grades">
<table>
<thead>
<tr>
<th>Subject</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<?php $unos = $baza->odradi("SELECT subject FROM subjects ORDER BY id ASC");
if (!empty($unos)) {
foreach($unos as $row=>$value){ ?>
<tr>
<td><input type="hidden" name="subject_id[]" value="<?= $unos[$row]["id"]; ?>"> <?= $unos[$row]["subject"]; ?></td>
<td>
<select class="form-control input-xs" name="grade_id[]" required>
<option selected disabled>Select grade</option>
<option value="5">excelent</option>
<option value="4">very good</option>
<option value="3">good</option>
<option value="2">ok</option>
<option value="1">bad</option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" name="grades" class="btn btn-success btn-lg" value="Submit grades">
</form>
And function which from where it needs to be saved looks like this:
if (isset($_POST['grades'])) {
foreach (array_combine($_POST['subject_id'], $_POST['grade_id']) as $i => $val){
$subject = $_POST["subject_id"][$i];
$grade = $_POST["grade_id"][$i];
$sql = "INSERT INTO final_grade (subject_id,grade_id) VALUES ('$subject','$grade')";
$u = mysqli_query($db, $sql);
}
But it's all messed up,in first two rows there is no grade or subject saved, and all some rows are missing completely.
Because you are calling array_combine(), your loop is not passing the subarray indexes as $i anymore. It is passing the subject_id as $i and grade_id as $val. You could have just used $i and $val as the values to insert rather than trying to re-access the $_POST arrays with $i.
Cleaner scripting would be to use the ids as hardcoded element keys on each <select> instead of passing a hidden field.
<?php
$options = [
5 => 'excellent',
4 => 'very good',
3 => 'good',
2 => 'ok',
1 => 'bad'
];
?>
<td><?= $unos[$row]["subject"]; ?></td>
<td><select class="form-control input-xs" name="grade[<?= $unos[$row]["id"]; ?>]" required>
<option disabled>Select grade</option>
<?php
foreach ($options as $opt_id => $opt_val) {
echo "<option value=\"{$opt_id}\">{$opt_val}</option>";
}
?>
</select>
</td>
Then you can simply access the associative submission.
if (isset($_POST['grade'])) {
// use prepared statement and bind variables
foreach ($_POST['grade'] as $id => $val) {
// execute prepared statement with each iteration
}
}
Alternatively, you could build up a single batch of results and do a single INSERT (I'd probably do it this way).
Suggested batch insert code:
$placeholders = [];
$params = ['']; // instantiate with no types in first element
foreach ($_POST['grade'] as $subject_id => $grade_id) {
$placeholders[] = '(?,?)'; // all necessary placeholders for the row
$params[0] .= 'ii'; // because you are passing 2 integer values per batch
array_push($params, $subject_id, $grade_id);
}
// execute single batch of inserts
$query = "INSERT INTO final_grade (subject_id,grade_id) VALUES " . implode(',', $placeholders);
$stmt = $conn->prepare($query);
$stmt->bind_param($params);
$stmt->execute();
The truth is, there are a number of ways that you can pass the data from your form and a number of ways that you can execute the INSERT query. I won't bother to write out all of the variations -- do what you like ...but definitely write stable/secure queries.

Codeigniter 3: Insert array form to database

I'm new with Codeigniter and I'm having some trouble inserting arrays into my database. An error kept popping out that I can't insert array to my database.
Here's my HTML form:
<?= form_open('profile/profile_submit'); ?>
<table class="table table-hover table-striped table-responsive">
<thead>
<tr>
<th id="headCheckHide"></th>
<th><center>Name</center></th>
<th><center>Date of Birth</center></th>
<th><center>Occupation</center></th>
<th><center>Educ. attainment</center></th>
</tr>
</thead>
<tbody id="sibTable">
<tr class="product-item">
<td>
<input type="text" class="form-control form-input" name="siblingName[]">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingBirthDate[]">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingOccupation[]">
</td>
<td>
<select class="form-control form-input" name="siblingEducAttainment[]" >
<option value="" selected>-Please select-</option>
<option value="less than high school">less than high school</option>
<option value="Some college but no degree">Some college but no degree</option>
<option value="Associates Degree">Associates Degree</option>
<option value="Elementary Graduate">Elementary Graduate</option>
<option value="Secondary Graduate">Secondary Graduate</option>
<option value="College Graduate">College Graduate</option>
<option value="Master's Degree">Master's Degree</option>
<option value="Professional Degree">Professional Degree</option>
<option value="Doctorate Degree">Doctorate Degree</option>
</select>
</td>
</tr>
</tbody>
</table>
<?= form_submit('submit','Save', 'class="btn btn-outline-primary waves-effect"');?>
<?php echo form_close();?>
My Controller for the form
public function profile_submit(){
$siblings=array(
'name' => $this->input->post('siblingName'),
'birthDate' => $this->input->post('siblingBirthDate'),
'occupation' => $this->input->post('siblingOccupation'),
'educAttainment' => $this->input->post('siblingEducAttainment')
);
$this->profile_model->submit_profile($siblings);
redirect('profile','refresh'); //name of the html file
}
My model for (profile_model.php)
function submit_profile($siblings){
$this->db->insert('tbl_st_profile_sibling',$siblings);
}
this is my model with the error: can't insert array into database.
Can anyone please help? thank you.
I think you need to insert multiple input data at a time with the same name, don't worry please follow my instructions as given below
Changes in Controller:
public function profile_submit(){
$submit_status = $this->profile_model->submit_profile();
if( $submit_status == "TRUE"){
redirect('profile','refresh'); //name of the html file
}else{
// Do Something else..
}
}
Changes in Model:
function submit_profile(){
$siblingsCount = count($this->input->post('siblingName'));
if($siblingsCount != null){
$itemValues=0;
$query = "INSERT INTO tbl_st_profile_sibling(name,birthDate,occupation,educAttainment) VALUES ";
$queryValue = "";
for($i=0;$i<$siblingsCount;$i++) {
$name = $this->input->post('name');
$birthDate = $this->input->post('birthDate');
$occupation = $this->input->post('occupation');
$educAttainment = $this->input->post('educAttainment');
if(!empty($name[$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $name[$i] . "', '" . $birthDate[$i] . "', '" . $occupation[$i] . "', '" . $educAttainment[$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
if (!$this->db->query($sql)) {
echo "FALSE";
}else {
echo "TRUE";
}
}
}
}
I hope this may help you...Thanks!
If you need to store array data into DB you need to use loops to insert one.
function submit_profile($siblings){
foreach($siblings['name'] as $key => $siblingName) {
$dataToSave = array(
'name' => $siblingName,
'birthDate' => $siblings['siblingBirthDate'][$key],
'occupation' => $siblings['siblingOccupation'][$key],
'educAttainment' => $siblings['siblingEducAttainment'][$key]
);
$this->db->insert('tbl_st_profile_sibling', $dataToSave);
}
}
UPDATE : Even you can use insert_batch to skip insertion in loop
function submit_profile($siblings){
foreach($siblings['name'] as $key => $siblingName) {
$dataToSave[] = array(
'name' => $siblingName,
'birthDate' => $siblings['siblingBirthDate'][$key],
'occupation' => $siblings['siblingOccupation'][$key],
'educAttainment' => $siblings['siblingEducAttainment'][$key]
);
}
$this->db->insert_batch('tbl_st_profile_sibling', $dataToSave);
}
The issue is not with the array you are saving into database the actual issue is with the post fields thy are in array format siblingName[]. So you need to convert then into strings so that this can be saved easily.
convert the array into coma separated list and then save in database.
$siblingName = implode(",",$_POST['siblingName']);
$siblingBirthDate= implode(",",$_POST['siblingBirthDate']);
$siblingOccupation= implode(",",$_POST['siblingOccupation']);
$siblingEducAttainment= implode(",",$_POST['siblingEducAttainment']);
$siblings=array(
'name' => $siblingName,
'birthDate' => $siblingBirthDate,
'occupation' => $siblingOccupation,
'educAttainment' => $siblingEducAttainment
);
<input type="hidden" name="count" value="<?php echo count($var); ?>" />
for($i=0;$i < count($var);$i++)
{
<tr class="product-item">
<td>
<input type="text" class="form-control form-input" name="siblingName<?php echo $i; ?>">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingBirthDate<?php echo $i; ?>">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingOccupation<?php echo $i; ?>">
</td>
<td>
<select class="form-control form-input" name="siblingEducAttainment<?php echo $i; ?>" >
<option value="" selected>-Please select-</option>
<option value="less than high school">less than high school</option>
<option value="Some college but no degree">Some college but no degree</option>
<option value="Associates Degree">Associates Degree</option>
<option value="Elementary Graduate">Elementary Graduate</option>
<option value="Secondary Graduate">Secondary Graduate</option>
<option value="College Graduate">College Graduate</option>
<option value="Master's Degree">Master's Degree</option>
<option value="Professional Degree">Professional Degree</option>
<option value="Doctorate Degree">Doctorate Degree</option>
</select>
</td>
</tr>
}
$count = $this->input->post('count');
for($i=0;$i < $count;$i++)
{
$siblings=array(
'name' => $this->input->post('siblingName'.$i),
'birthDate' => $this->input->post('siblingBirthDate'.$i),
'occupation' => $this->input->post('siblingOccupation'.$i),
'educAttainment' => $this->input->post('siblingEducAttainment'.$i)
);
$this->profile_model->submit_profile($siblings);
}

Inserting an array into a relational table

I have 3 tables:
user_login
doc_list
user_cat_link_table
So I am creating a new user and apart of the form shows an array of the available categories which are pulled from the cat_list table.
I am struggling to along with the other form data update the user_cat_link_table.
The script to take the ID of the new user and take the ID of the category selected from the checkboxes array:
Here is my input form:
<form action="actions/add_emp.php" method="post">
<input type="text" name="user" placeholder="Username" required="required" /><br/>
<input type="text" name="pass" type="password" placeholder="Password"/></label><br/>
<input type="text" name="firstname" id="name" required="required"
placeholder="Firstname"/><br />
<input type="text" name="lastname" id="email" required="required"
placeholder="Lastname"/><br/>
<input type="email" name="email" id="city" required="required"
placeholder="Email Address"/><br/>
<input type="text" name="extension" id="extension" required="required"
placeholder="Extension Number"/><br/>
<select name="title">
<option selected disabled>Please Select a Job Title...</option>
<option disabled></option>
<option disabled>Helpesk:</option>
<option value="Technical Support Advisor">Technical Support Advisor</option>
<option value="Deputy Team Leade">Deputy Team Leader</option>
<option value="Team Leader">Team Leader</option>
<option value="Incident Resolution Advisor">Incident Resolution Advisor
</option>
<option disabled></option>
<option disabled>Call Centre:</option>
<option value="Technical Support Advisor">Technical Support Advisor</option>
<option value="">Deputy Team Leader</option>
<option value="">Team Leader</option>
<option disabled></option>
</select>
<div id="checkboxlist" >
<?php
foreach($category as $cat){
?>
<input type="checkbox" value="<?php echo $cat["cat_id"]; ?>"
name="cat_no[]" id="box1"> <?php echo $cat["cat_title"]; ?></a><br>
<?php
}
?>
</div>
<input type="submit" value="Add User" name="submit"/><br />
</form>
I can see if I do a print_r() or var_dump() I am getting the results I expect:
Array ( [action] => id
[user] => test23wer3e4weret4essd
[pass] => test [firstname] => test
[lastname] => test
[email] => tes#test.com
[extension] => 1234
[cat_no] => Array ( [0] => 69
[1] => 70
[2] => 71 )
[submit] => Add User )
Here is the form which acts as the script to insert the data into both the user_login table (which works) but its the part at the bottom trying to insert into the join table I am having trouble with:
<?
session_start();
session_regenerate_id();
if(!ini_get('date.timezone'))
{
date_default_timezone_set('GMT');
}
if(isset($_POST["action"])){
if(isset($_POST['submit'])){
include_once'../../config.php';
$dbh = new PDO("mysql:host=$hostname;dbname=dashboardr",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['user']) && isset($_POST['pass'])){
$password=$_POST['pass'];
$sql=$dbh->prepare("SELECT COUNT(*) FROM `user_login` WHERE `username`=?");
$sql->execute(array($_POST['user']));
if($sql->fetchColumn()!=0){
die("User Exists");
}else{
function rand_string($length) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
$p_salt = rand_string(20);
$site_salt="subinsblogsalt";
$salted_hash = hash('sha256', $password.$site_salt.$p_salt);
$sql=$dbh->prepare("INSERT INTO `user_login`
(`id`, `username`, `password`, `psalt`,
`firstname`, `lastname`, `email`, `extension`)
VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)");
$sql->execute(
array($_POST['user'], $salted_hash, $p_salt, $_POST["firstname"],
$_POST["lastname"], $_POST["email"], $_POST["extension"]));
print_r($_POST);
die();
$docId = $dbh->lastInsertId();
$sql = "INSERT INTO `user_cat_link_table`(`UserID`, `Cat_ID`) VALUES";
$values = "";
$params = [];
foreach($_POST["cat_no"] as $cat)
{
$values.= "(?, ?), ";
$params[] = $cat; // correct here
$params[] = $docId;
}
$values = substr($values, 0, -2);
$sql.= $values;
$query = $dbh->prepare($sql);
$query->execute($params);
if ($dbh->query($sql)) {
}else{}
$dbh = null;
} //catch(PDOException $e)
header ('Location: ../list_doc.php?success=1');
}
}
}
?>

Get state name from drop down list after click submit button (part 3)

Cont. on Pass city name from php to js (part 2)
State data json ($stateJsonObject):
Array (
[0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur)
[1] => stdClass Object ( [stateId] => s2 [stateName] => Selangor)
)
Code (stateName):
<html>
<head></head>
<body>
<form action="test3.php" method="post">
State:
<select name="state" id="state" onchange="showCity(this, 'city')">
<option value ="">select one</option>
<?php
for($i = 0; $i < count($stateJsonObject); $i++)
{
echo '<option value = '.$stateJsonObject[$i] -> stateId.'>';
echo $stateJsonObject[$i] -> stateName;
echo '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
My question is:
When I choose Selangor from drop down list, after I click submit button, how do I keep the Selangor name in the drop down list selected?
If this is submitted on the same page, you could add the currently submitted entry and put a checked attribute inside the loop:
<form action="test3.php" method="post">
State:
<select name="state" id="state" onchange="showCity(this, 'city')">
<option value ="">select one</option>
<?php
for($i = 0; $i < count($stateJsonObject); $i++)
{
$selected = ($stateJsonObject[$i]->stateId == $_POST['state']) ? 'checked' : '';
echo "<option value='".$stateJsonObject[$i]->stateId."' $selected>";
echo $stateJsonObject[$i] -> stateName;
echo '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
Or with a foreach variant:
foreach($stateJsonObject as $state) {
$stateId = $state->stateId;
$stateName = $state->stateName;
$selected = ($stateId == $_POST['state']) ? 'checked' : '';
echo "<option value='$stateId' $selected>$stateName</option>";
}

PHP: How to correctly loop through multi-dimen post arrays

If I have a form with fields like this.
THERE WILL BE MULTIPLE ROWS OF THESE FIELDS HENCE THE SQUARE BRACKETS
<input type="text" name="txt-receipt-number[]" value="" />
<input type="text" name="txt-stock-number[]" value="" />
<input type="text" name="txt-repair-code[]" value="" />
How do I loop through the $_POST variable to get the values because its getting the field names but not the values, what am I doing wrong please?
$fields = array();
$values = array();
foreach($_POST as $field => $value) {
$fields[] = $field;
echo $value;
}
Output:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Update:
Sorry, quick edit for correct output...
Further Update:
Lets ignore the insert, how do I get the values please?
Remove the [] of your text input, or you will get $value of array type.
<input type="text" name="txt-receipt-number" value="" />
<input type="text" name="txt-stock-number" value="" />
<input type="text" name="txt-repair-code" value="" />
And don't forget to quote your values.
foreach($_POST as $field => $value)
{
if(is_array($value))
{
foreach($value as $k => $val)
{
echo $val;
}
}
else
{
echo $value;
}
}
Works for regular fields and one-dimensional _POST fields.
You will have some other problems though, with column names like sales_receipt-number, etc. You should enclose those in backquotes, and you must also escape them since they are going directly into your SQL statement. They are just as vulnerable to SQL injection as the VALUES().
$fields[] = "`" . mysql_real_escape_string($field) . "`";
Update 2
To get the values and do the insert in a loop, the SQL needs to be reconstructed each time in the loop, using one set of array values.
// Find the number of loops necessary
// Unless all fields are always required, this will need to be the $_POST key with the most values
$numLoops = count($_POST['txt-receipt-number']);
fields = array();
$values = array();
for ($i = 0; $i < count($_POST); $i++) {
foreach($_POST as $field => $value) {
$fields[] = "`" . mysql_real_escape_string($field) . "`";
$values[] = mysql_real_escape_string($_POST[$field][$i]);
// Now build the SQL for this loop iteration.
$sql = 'insert into table(' . join(',', $fields) . ') values(' . join(',', $values) . ')';
}
}
To be honest, I see many problems in this code...
Using foreach to build dynamic list of fields that need to be inserted. Don't you have, for example, anything like <input type='submit' name='add_data'/>? It's common to have submit buttons, and, with your code, you would try to edit DB table's field named add_data. This is also unsafe, as it (a) reveals table structure and (b) gives possibility to make SQL errors by manually changing field names, which may lead to another security/stability issues.
Lack of escaping field names. May lead to SQL injections.
Using - sign in field names. insert into table(sales_receipt-number, ... just won't work.
As for handling posted arrays...
<form method='post' action=''>
<table border='1'>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td colspan='3'>
<input type='submit' name='add_items'/>
</td>
</tr>
</table>
</form>
<pre>
<?php
function handleAddingItem() {
if ( !isset($_POST['receipt_number'], $_POST['stock_number'], $_POST['repair_code']) ) {
trigger_error("Some field is undefined");
return false;
}
if ( !is_array($_POST['receipt_number']) || !is_array($_POST['stock_number']) || !is_array($_POST['repair_code']) ) {
trigger_error("Some field is not an array");
return false;
}
$keys = array_keys($_POST['receipt_number']);
if ( array_keys($_POST['stock_number']) !== $keys || array_keys($_POST['repair_code']) !== $keys ) {
trigger_error("Posted arrays have different keys");
return false;
}
foreach ( $keys as $key ) {
if ( empty($_POST['receipt_number'][$key]) && empty($_POST['stock_number'][$key]) && empty($_POST['repair_code'][$key]) ) {
continue;
}
$receiptNumber = mysql_real_escape_string($_POST['receipt_number'][$key]);
$stockNumber = mysql_real_escape_string($_POST['stock_number'][$key]);
$repairCode = mysql_real_escape_string($_POST['repair_code'][$key]);
$sql = "
insert into table_name set
receipt_number = '{$receiptNumber}',
stock_number = '{$stockNumber}',
repair_code = '{$repairCode}'
";
echo $sql;
}
return true;
}
function handlePost() {
print_r($_POST);
if ( isset($_POST['add_items']) ) {
handleAddingItem();
}
}
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
handlePost();
}
?>
Output:
Array
(
[receipt_number] => Array
(
[0] => 123
[1] =>
[2] =>
)
[stock_number] => Array
(
[0] =>
[1] =>
[2] =>
)
[repair_code] => Array
(
[0] =>
[1] =>
[2] =>
)
[add_items] => Submit Query
)
insert into table_name set
receipt_number = '123',
stock_number = '',
repair_code = ''
Common practice might be to pass additional field - row's ID. If it has a value, then action is "edit", if it is empty, action is "create".
This is a little bit strange but try it :
<?php
foreach($_POST['txt-receipt-number'] as $k=>$v){
$array[$k]['txt-receipt-number'] = $_POST['txt-receipt-number'][$k];
$array[$k]['txt-stock-number'] = $_POST['txt-stock-number'][$k];
$array[$k]['txt-repair-code'] = $_POST['txt-repair-code'][$k];
}
$fields = array();
$values = array();
foreach($array as $row) {
foreach($row as $field => $value) {
$values[] = $value;
$fields[] = $field;
}
}
var_dump($fields);
var_dump($values);
?>
<form method='post' action=''>
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
----
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
<input type="submit" value="go">
</form>

Categories