This is my html codes for dynamic table rows. This duplicate the table fields by clicking the Add new button. The problem is I cannot insert all the filled data into the database. It would be nice if you can help me. Thanks a lot.
<!-- Time&Task -->
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<br>
<table class="table table-striped" id="maintable" width="50%" cellpadding="0" cellspacing="0" class="pdzn_tbl1" border="0px">
<tr>
<th>Time Start:</th>
<th>Time End:</th>
<th>Task:</th>
<th>Comment:</th>
</tr>
<tr class="rows">
<td style="padding:5px;">
<input type="time" name="item[0][timestart]" />
</td>
<td style="padding:5px;">
<input type="time" name="item[0][timeend]" />
</td>
<td style="padding:5px;">
<input type="text" name="item[0][tasks]" />
</td>
<td style="padding:5px;">
<input type="text" name="item[0][comment]" />
</td>
</tr>
</table>
<div id="add_new">ADD NEW</div>
<?php
if (isset($_POST['item']) && is_array($_POST['item'])) {
$items = $_POST['item'];
$i = 0;
foreach($items as $key => $value) {
echo 'Item '.$i++.': '.$value['timestart'].' '.$value['timeend'].' '.$value['tasks'].' '.value['comment'].'<br />';
}
}
?>
</div>
</div>
</div><!-- /.box-body -->
This is my sql query for inserting. here is the problem. I don't know how to loop to insert into the DB. Thanks. :D
<?php
if (isset($_POST['data']) && !empty($_POST['data'])) {
$timestart = htmlspecialchars($_POST['timestart']);
$timeend = htmlspecialchars($_POST['timeend']);
$tasks = htmlspecialchars($_POST['tasks']);
$comment = htmlspecialchars($_POST['comment']);
include('DBConnect.php');
$SQL = "INSERT INTO TSTable (timestart,timeend,tasks,comment) VALUES ('$timestart','$timeend','$tasks','$comment')";
if (mysqli_query($conn, $SQL)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
! Hi all, I found a solution already. Here are the correct codes. I hope it helps someone who needs it.
The html is still the same and only sql query part needed to fix.
if (isset($_POST['data'])) {
$timestart = $_POST['timestart'];
$timeend = $_POST['timeend'];
$tasks = $_POST['tasks'];
$comment = $_POST['comment'];
include('DBConnect.php');
$count= count($timestart);
for ($i=0; $i< $count; $i++){
if($timestart[$i] != null || !empty($timestart[$i])){
$SQL = "INSERT INTO TSTable (timestart,timeend,tasks,comment) VALUES ( '$timestart[$i]','$timeend[$i]','$tasks[$i]','$comment[$i]')";
}
if (mysqli_query($conn, $SQL)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
There are a few things here that will make your life easier if changed.
Input elements with the same name will be submitted as an array, in the order they appear. Standard procedure is to layout your html like so (a few fields removed for brevity);
<td><td><input name=timestart><input name=timeend><input name=tasks></td></tr>
<td><td><input name=timestart><input name=timeend><input name=tasks></td></tr>
<td><td><input name=timestart><input name=timeend><input name=tasks></td></tr>
... etc
This will give you a post structure such as ;
Array
(
[timestart] => Array
(
[0] => timestart 1
[1] => timestart 2
[2] => timestart 3
)
[timeend] => Array
(
[0] => timeend 1
[1] => timeend 2
[2] => timeend 3
)
[task] => Array
(
[0] => task 1
[1] => task 2
[2] => task 3
));
And insert with;
$timestart = $_POST['timestart'];
$timeend = $_POST['timeend'];
$task = $_POST['task'];
for($i=1 ; $i < count($timestart) ; $i++)
{
$sql = "INSERT INTO TSTable VALUES($timestart[$i],$timeend[$i],$task[$i]);"
... more code goes here..
}
Related
Insert HTML Form array into database rows in mySQL with PHP
i am inserting html array into database using for and foreach
problem inserting data in to database using for loop its inserting blank data
please help. please give advice on it or give solution thank you in advance
i have tried the below code or any different method using for it.
php file
if(isset($_POST['submitmultiple']))
{
$course_id = $_POST['course_id'];
$topic_name = $_POST['topic_name'];
$topic_description = $_POST['topic_description'];
$parent_id = $_POST['parent_id'];
echo count($course_id);
if(!empty($course_id))
{
for($i = 0; $i < count($course_id); $i++)
{
/*if(!empty($course_id[$i]))
{*/
foreach ($_POST['course_id'] as $value)
{
$course_id = $course_id[$i];
$topic_name = $topic_name[$i];
$topic_description = $topic_description[$i];
$parent_id = $parent_id[$i];
$sql = "INSERT INTO syllabus (course_id,topic_name,topic_description,parent_id) VALUES ('$course_id','$topic_name','$course_description','$parent_id')";
if($connect->query($sql) === TRUE)
{
$valid[1] = "Added Successfully";
}
else
{
$valid[2] = "Error while Inserting";
}
}
/*}*/
}
}
}
html code
<form id="submitMultipleData" class="submitMultipleData" role="form" name="hl_form" method="post" >
<div class="box-body">
<div class="row">
</div>
<!-- /.row -->
<table class="table table-bordered table-striped table-condensed table-hover" id="dynamic_field">
<th>Course Name</th>
<th>Topic Name</th>
<th>Description</th>
<th>Parent Topic Name</th>
<th>Action</th>
<tr id="id" class="trrow">
<td class="col-md-4">
<select class="form-control select2 selectCourse" data-id="1" id="course_id_1" name="course_id[]" data-live-search="true" >
<option value="" selected="selected"> Select Course Name</option>
<?php
$sql = "SELECT * from course_master";
$result = $connect->query($sql);
while($row_pt = $result->fetch_array())
{
?>
<option value="<?php echo $row_pt['course_id']; ?>"><?php echo $row_pt['course_name']; ?></option>
<?php
}
?>
</select >
</td>
<td class="col-md-2"> <input class="form-control topic_name" id="topic_name1" name="topic_name[]" maxlength="250" value="" placeholder="Enter Topic Name" type="text" ></td>
<td class="col-md-4"><textarea class="form-control" style="resize: none;" id="topic_description1" name="topic_description[]" rows="3" placeholder="Enter Description"></textarea></td>
<td class="col-md-2"><select class="form-control select2" id="parent_id_1" name="parent_id[]" data-live-search="true" ></select></td>
<td class="col-md-2"><input type="button" name="add" value="Add Row" class="btn btn-success"></td>
</tr>
</table>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submitmultiple" id="button" class="btn btn-primary btn-form-action btn-submit">Save</button>
</div>
</form>
Assuming the value at indexes is related for course/topic/parent, etc.
You can skip one of the for loops too.
if(isset($_POST['submitmultiple']))
{
$course_id = $_POST['course_id'];
$topic_name = $_POST['topic_name'];
$topic_description = $_POST['topic_description'];
$parent_id = $_POST['parent_id'];
echo count($course_id);
if(!empty($course_id))
{
foreach ($_POST['course_id'] as $key => $value)
{
$tempcourse_id = $course_id[$key];
$temptopic_name = $topic_name[$key];
$temptopic_description = $topic_description[$key];
$tempparent_id = $parent_id[$key];
$sql = "INSERT INTO syllabus (course_id,topic_name,topic_description,parent_id) VALUES ('$tempcourse_id','$temptopic_name','$temptopic_description','$tempparent_id')";
//Verify the query formed
echo $sql."\n";
if($connect->query($sql) === TRUE)
{
$valid[1] = "Added Successfully";
}
else
{
$valid[2] = "Error while Inserting";
}
}
}
}
1) your question is not clear - dont understand how sending multiple cources
add multiple here
select
to
select multiple
2) add single quotes along fields
(course_id,topic_name,topic_description,parent_id)
to
('course_id','topic_name','topic_description','parent_id')
after changing these few changes i can see this query by submitting form
INSERT INTO syllabus ('course_id','topic_name','topic_description','parent_id') VALUES ('c2','asd','','1')
query seems fine - should insert data
I have a form like this
<form class="product-data" action="">
<table>
<tr class="data-row">
<td>
<input type="number" name="finance[a][source_unit]" >
</td>
<td >
<input type="number" name="finance[a][target_unit]">
</td>
<td>
<input type="number" name="finance[a][client_price]">
</td>
<td>
<input type="number" name="finance[a][client_salary]" >
</td>
</tr>
<tr class="data-row">
<td>
<input type="number" name="finance[b][source_unit]" >
</td>
<td >
<input type="number" name="finance[b][target_unit]">
</td>
<td>
<input type="number" name="finance[b][client_price]">
</td>
<td>
<input type="number" name="finance[b][client_salary]" >
</td>
</tr>
</table>
</form>
here you can see I have two rows. One for a and another for b. Now I want to save them in the database with two rows. One for the a and another for b at a same time. When I am doing print_r(finance). with this code
$finances = $_POST['finance'];
print_r($finances);
Its showing me an array like this
Array
(
[a] => Array
(
[source_unit] => 3213
[target_unit] => 657654322343
[client_price] => 5435.00
[client_salary] => 897.00
)
[a] => Array
(
[source_units] => 67656565
[target_units] => 43243
[client_price] => 23432.00
[client_salary] => 6546.00
)
)
Now can someone tell me how to save them in each row. I have my database table is like this and the data should be saved like this
Id, product_type, source_unit, target_unit, client_price, lient_salary
1 A 3213 657654322343 5435 897
2 B 67656565 43243 23432 6546
I have two solutions for you. Once that is tailored for this scenario only:
$f = $_POST['finance'];
// insert first row
$query = "INSERT INTO `table` VALUES (NULL, 'A', {$f['a']['source_unit']}, {$f['a']['target_units']}, {$f['a']['client_price']}, {$f['a']['client_salary']})";
mysql_query($query);
// insert second row
$query = "INSERT INTO `table` VALUES (NULL, 'B', {$f['b']['source_unit']}, {$f['b']['target_units']}, {$f['b']['client_price']}, {$f['b']['client_salary']})";
mysql_query($query);
or if you have it more universal (for multiple rows):
$f = $_POST['finance'];
foreach($f as $key => $item) {
// assign key of the letter as value to insert
$letter = strtoupper($key);
// insert a row
$query = "INSERT INTO `table` VALUES (NULL, '{$letter}', {$item['source_unit']}, {$item['target_units']}, {$item['client_price']}, {$item['client_salary']})";
mysql_query($query);
}
loop thru your array and either insert or update accordingly.
foreach($finances as $key => $data)
{
//based on the $key if value exists in database update else insert
echo $key.'<br />';
echo $data['source_unit'].'<br />';
echo $data['target_unit'].'<br />';
echo '<hr />';
}
sir ,
I have two textbox in my form.
My data is like...
column1 price
501 1
502 2
503 3
504 1
505 2
506 3
507 1
like wise...
I need to update all value of price column from inputed textbox value.
for Ex Inputted values in textbox like
monthtextbox = 1
pricetextbox = 50 then
update all 1 with 50 in price column.
below is my code but this is not updating any values.plz suggest me an update statement.
<?php
$errors = array();
if(isset($_POST['update']))
{
$month = $_POST['month'];
$price = $_POST['price'];
$modified = date("Y-m-d H:i:s");
$updaterow = $database->updateRow("UPDATE scheme_master SET price = :price WHERE price = :price",
array(':price'=>$price,':price'=>$month,':modified'=>$modified));
$_SESSION['message'] = "Data Updated Successfully";
}
?>
<form name="frm2" method="post" action="">
<div id="page-wrap">
<table height="50">
<tr>
<td width="8%">Enter Month :</td>
<td width="19%"><input type="text" name="month" class="" required = "" /></td>
<td width="11%">Enter Price :</td>
<td width="20%"><input type="text" name="price" class="" required = ""/></td>
<td width="12%" height="45"><input type="submit" name="update" value="Save"/></td>
</tr>
</table>
</div>
</form>
Change price column with month in where condition and also an array.
this will update all values and work for you.
<?php
$errors = array();
if(isset($_POST['update']))
{
$month = $_POST['month'];
$price = $_POST['price'];
$updaterow = $database->updateRow("UPDATE scheme_master SET price = :price WHERE price = :month",
array(':price'=>$price,':month'=>$month));
$_SESSION['message'] = "Data Updated Successfully";
}
?>
thank you for your answer meanwhile i got this code for inserting the multiple data, and it really works but my problem is it adds the fisrt column then after finished then it executes the second column i want them to excecute insert f1 then f2 then f1 then f2 again:
just imagine i have 4 input with same name f1 and f2
Inserting multiple entries into table from the same form please refer on this post
Your are missing names in all of your form fields
/*PHP code where the form submit, and repeat the same for other fields like descriptionField*/
<?php
for($i = 0; $i <= count ( $_POST ['dateField'] ); $i ++) {
// Do what ever you want with data
var_dump ( $_POST ['dateField'] [$i] );
}
?>
HTML Code, names added
<tr class="item-row">
<td class="item-name"><div class="delete-wpr">
<textarea>Date</textarea>
<a class="delete" href="javascript:;" title="Remove row">X</a>
</div></td>
<td class="description"><textarea name="descritpionField[]">Description</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="asd">0</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="qty">0</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="cost">0</textarea></td>
<td style="text-align: center;"><span class="price">0</span></td>
</tr>
If i understand correctly
If this fields in form, then set 'name' attr to fields like name="user[]"
When u'll submit the form, all values of "user[]" fields will in array. Just do print_r() and you will see, what i try to explain
Also u can do it in javascript. . .
Just grab all values in array. . .
User "Noor" already post example for you
Please try this code,
<?php
echo "<pre>";
if(isset($_POST['submit'])){
print_r($_POST['data']);//RESULT WILL GET AN ARRAY
}
?>
<form action="" method="post">
<table>
<?php
//$items = // DATA FROM DB
//$items_count = count($items);
$items_count = 5;
for($i=0;$i<$items_count;$i++) {
?>
<tr class="item-row-<?php echo $i;?>">
<td class="item-name"><div class="delete-wpr"><textarea name="data[<?php echo $i;?>]['date']">Date</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea name="data[<?php echo $i;?>]['description']">Description</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['age']" style="text-align:center;" class="asd">0</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['dob']" style="text-align:center;" class="qty">0</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['status']" style="text-align:center;" class="cost">0</textarea></td>
<td style="text-align:center;" ><span class="price">0</span></td>
</tr>
<?php } ?>
<table>
<input type="submit" class="button" name="submit" value="submit" />
</form>
Answer fo the post (Trouble with $_POST [duplicate])
I don't know if I understand your concern.
I think you are trying to create a quiz. And so the user must validate several attempts. your problem is that you can not accumulate the different answers following a table. so here is a solution.
<?php
$good_answers = array(
"easy1" => array("4","3","5","2","6","9","7","8","1" ),
"easy2" => array("6","8","2","5","7","1","4","9","3" ),
"easy3" => array("1","9","7","8","3","4","5","6","2" ),
"easy4" => array("8","2","6","1","9","5","3","4","7" ),
"easy5" => array("3","7","4","6","8","2","9","1","5" ),
"easy6" => array("9","5","1","7","4","3","6","2","8" ),
"easy7" => array("5","1","9","3","2","6","8","7","4" ),
"easy8" => array("2","4","8","9","5","7","1","3","6" ),
"easy9" => array("7","6","3","4","1","8","2","5","9" )
);
if(isset($_POST['row'])){
$easy = false;
$client_responses = $_POST['row']; // EX: [" "," "," " ,"2","6"," " ,"7"," " ,"1"]
$old = json_decode($_POST['old']);
$old[] = $client_responses;
// Or make array_push($old,$client_responses); if you prefere
foreach ($good_answers as $easy => $responses) {
if($client_responses === $responses){
$easy = $responses;
break;
}
}
// generating table for HTML of client responses
echo '<table>';
// saving old responses
echo '<input type="hidden" value="'. json_encode($old) .'" name="old">';
foreach ($old as $number => $row) {
echo '<tr id="row'. $number .'">';
for ($i=0; $i < count($row); $i++) {
echo '<td class="cellTop">';
echo '<input type="text" maxlength="1" name="row" value="'. $row[$i].'"/>';
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
}
Here is the form that collects employer's history and stores that data into 2d array, then I am trying to store that info into mysql database in a table employment. It gives me no error but it can't store data into mysql ..
form1.php
<form action="result.php" method="post">
<table width="676" border="0" cellspacing="0" cellpadding="7" align="center">
<tr><td colspan="6" bgcolor="#C0C0C0">EMPLOYMENT HISTORY</td></tr>
<?php
for ($x=0; $x<2; $x++)
{
?>
<tr>
<td colspan="3" align="left">NAME OF EMPLOYER<br>
<input type="text" name="emp[emp_name][]" size="38"></td>
<td align="left">JOB TITLE <br>
<input type="text" name="emp[emp_title][]" size="32"></td>
</tr>
<tr>
<td colspan="5" valign="top">ADDRESS<br>
<input type="text" name="emp[emp_addr][]" size="58"></td>
</tr>
<tr>
<td colspan="2" valign="top">REASON FOR LEAVING<br>
<textarea name="emp[emp_reason][]" cols="25" rows="3"></textarea></td>
</tr>
<tr>
<td align="left">DATE STARTED<br>
<input type="text" name="emp[emp_start][]" size="8"></td>
<td align="left">DATE ENDED<br>
<input type="text" name="emp[emp_end][]" size="8"></td>
<td colspan="2" align="left">TYPE OF BUSINESS<br>
<input type="text" name="emp[emp_btype][]" size="15"></td>
</tr>
<tr><td colspan="6" bgcolor="#C0C0C0"> </td></tr>
<?php } ?>
</table>
<input type="submit" name="submit" value="SUBMIT"> <input type="reset" value="RESET">
</form>
here is the result.php
<?php
// open connection to the database
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('userdb');
// get all the values
$app_id = 5;
$app_emp = array($emp => array(
$emp_name => $_POST["emp_name"],
$emp_title => $_POST["emp_title"],
$emp_addr => $_POST["emp_addr"],
$emp_reason => $_POST["emp_reason"],
$emp_start => $_POST["emp_start"],
$emp_end => $_POST["emp_end"],
$emp_btype => $_POST["emp_btype"]
));
// set up error list array
$errorList = array();
$count = 0;
// validate
// making sure that they are filling in all the required fields for the employer for each of the 3 "boxes"
for ($x=0; $x<sizeof($app_emp); $x++)
{
if(!empty($emp_name[$x]) || !empty($emp_start[$x]) || !empty($emp_end[$x]))
{
if(empty($emp_start[$x]) || empty($emp_end[$x]))
{
$errorList[$count] = "Invalid entry: Employment History, item " . ($x+1);
$count++;
}
}
}
// if no errors
if (sizeof($errorList) == 0)
{
// insert employment history
for($i=0; $i<sizeof($emp_name); $i++)
{
$x = 0;
if (!empty($emp_name[$i][$x]) && !empty($emp_start[$i][$x]) && !empty($emp_end[$i][$x]))
{
$query = "INSERT INTO `employment` (`app_id`,`name`,`title`,`addr`,`reason`,`start`,`end`,`bustype`) VALUES ('$app_id', '$emp_name[$x]', '$emp_title[$x]', '$emp_addr[$x]','$emp_reason[$x]', '$emp_start[$x]', '$emp_end[$x]', '$emp_btype[$x]')" or die(mysql_error());
$result = mysql_query($query, $conn) or die ("Error in query: $query. " . mysql_error());
}
}
// If it gets processed, print success code
echo "Your information has been accepted.";
}
else
{
?>
<table width="676" border="0" cellspacing="0" cellpadding="8" align="center">
<tr><td>
<?php
// or list errors
listErrors();
?>
</span></td>
</tr>
</table>
<?
}
?>
<?php
// print out the array
echo '<pre>';
print_r($_POST);
echo '</pre>';
?>
I know you have found a solution. Just incase someone found this and get curious :)
There are couple of issues with the logic
For start under this line:
// get all the values
$emp will be empty '' all the time as it is not initialised and if you initialise the entire logic will shatter.
Also the $_POST you have mentioned will always be empty. You need to address it from them Master (Level1) Just var_dump($_POST) and you see what I mean :)
So do something like this: (I must stress this is not a good approach but just to shed some light on this question)
var_dump($_POST['emp']); // This is master array that holds everything
$app_emp = array();
foreach ($_POST['emp'] as $key => $val) {
$app_emp[0][$key] = mysql_real_escape_string($val[0]);
$app_emp[1][$key] = mysql_real_escape_string($val[1]);
}
// set up error list array
$errorList = array();
$count = 0;
var_dump($app_emp);
Now in the $app_emp you have got 2 separate arrays that you can go through, validate and add them to DB. Of-course the current SQL is not going to work as you need to wiggle it to fit the new array. Rest should be easy.
Couple Of handy note:
I am sure you are cleaning up your form submit mysql_real_escape for
all the vars.
Also try to use redirection after successful submit,
as users will intend to refresh the page. Otherwise user is going to
get ugly do you want to resubmit the data.
Make sure you pass a token to the result page, and check it there. I would use a random DB number so stop the Cross Browser hacks.
Hope this help. H.