How to insert values into MySQL database from a dynamic html table? - php

I have this form in which user can add multiple rows depends on his/her preference. The name of each input tags were generated using jquery; meals1...amount1, meals2...amount2 and so on.
My question is how do I insert all those values into my MySQL database?
So far I have this function:
function dbRowInsert($table_name, $form_data)
{
// retrieve the keys of the array (column titles)
$fields = array_keys($form_data);
// build the query
$sql = "INSERT INTO ".$table_name."
(`".implode('`,`', $fields)."`)
VALUES('".implode("','", $form_data)."')";
// run and return the query result resource
return mysql_query($sql);
}
HTML:
<div id ="ca_meals"><!--start of ca_meals-->
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<h3>Meals Form</h3>
<div class="form-group">
<label for="ca_meals_date">Date:</label>
<input type="text" class="form-control" id="ca_meals_date" name="ca_meals_date" placeholder="Date">
</div>
<div class="form-group">
<label for="ca_meals">Purpose:</label>
<input type="text" class="form-control" id="ca_meals_purpose" placeholder="Purpose">
</div>
<table class="table table-bordered table-hover" id="tab_logic_meals">
<thead>
<tr >
<th class="text-center">
Meals
</th>
<th class="text-center">
Number of PAX
</th>
<th class="text-center">
Alloted Budget Per PAX
</th>
<th class="text-center">
Amount
</th>
</tr>
</thead>
<tbody>
<tr id='meals0'>
<td>
<input type="text" name='ca_accommodate' placeholder='Meals' class="form-control"/>
</td>
<td>
<input type="text" name='ca_meals_numberpax' placeholder='Number of PAX' class="form-control"/>
</td>
<td>
<input type="text" name='ca_meals_budgetpax' placeholder='Alloted Budget Per PAX' class="form-control"/>
</td>
<td>
<input type="text" name='ca_meals_amount' placeholder='Amount' class="form-control"/>
</td>
</tr>
<tr id='meals1'></tr>
</tbody>
</table>
<div class="form-group">
<label for="ca_total">Total:</label>
<input type="text" class="form-control" id="ca_total" disabled>
</div>
</div>
</div>
<a id="add_row_meals" class="btn btn-primary pull-left">Add Row</a><a id='delete_row_meals' class="pull-right btn btn-danger">Delete Row</a>
</div>
</div><!--end of ca_meals-->
This is my JQuery:
$("#add_row_meals").click(function(){
$('#meals'+l).html("<td><input name='ca_meal"+l+"' type='text' placeholder='Meals' class='form-control input-md' /> </td><td><input name='ca_meals_numberpax"+l+"' type='text' placeholder='Number of PAX' class='form-control input-md'></td><td><input name='ca_meals_budgetpax"+l+"' type='text' placeholder='Alloted Budget Per PAX' class='form-control input-md'></td><td><input name='ca_meals_amount"+l+"' type='text' placeholder='Amount' class='form-control input-md'></td>");
$('#tab_logic_meals').append('<tr id="meals'+(l+1)+'"></tr>');
l++;
});
$("#delete_row_meals").click(function(){
if(l>1){
$("#meals"+(l-1)).html('');
l--;
}
});

Usually it's done by passing arrays or indexes with the fields names.
Say, in JavaScript when you add a DHTML field for the name, call it meals[]
In PHP the $_POST['meals'] will contain an array then.
The other way - indexes. Say, when you create a new field with Javascript, give it a new name like meals_1, meals_2, etc. And then loop on them in PHP.
For the first case, with meals[], the POST request will be like:
&meals[]=aaa&meals[]=bbb&meals[]=ccc&amount[]=1&amount[]=2&amount[]=3
An example of PHP code working with meals[] would be:
for($i=0;$i<count($_POST['meals']);$i++)
{
$sql = "INSERT INTO ... SET
`meals` = ". $_POST['meals'][$i].",
`amount` = ". $_POST['amount'][$i].",
// etc
}

Related

PHP/MYSQL: Saving array data in table rows to mysql database using checkbox

I have an order table in my project. I am pulling the products from the database to this table using foreach. I show the quantity and unit price calculation information on the table instantly with jquery. I want to save the data in this table from the row selected with the checkbox to the database. I tried a few things with foreach but it looped so it created a new record for each row in the database. I want to print arrays with implode using commas between them. For example, the data in the rows entered in the quantity field in the table should be entered in the quantity field in the database as 1,2,3,4. If I have to explain briefly, I want to make an insert in one go.
Table:
Table & Form Code:
<form action="" method="POST">
<table class="table table-sm mb-3 text-center align-middle">
<thead>
<tr>
<th>Choose</th>
<th>Product Name</th>
<th width="137px">Quantity</th>
<th>Unit Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<?php foreach($ProductTbl as $product){ ?>
<tr>
<th scope="row">
<div class="form-check form-check-success">
<input class="form-check-input" name="check[]" type="checkbox" value="
<?= $product-> productid">
</div>
</th>
<td>
<?= $product->productname ?>
</td>
<td>
<input class=" w-25 text-center quantity" type="text" name="quantity[]" value="0">
</td>
<td>
<input class="w-25 text-center unitprice" type="text" name="unitprice[]" value="
<?= $product->unitprice ?>" disabled="disabled"> €
</td>
<td>
<input class="w-25 text-center totalprice" type="text" name="totalprice[]" value="" disabled="disabled"> €
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="text-center">
<button class="btn btn-success col-md-2" type="submit" name="add">Offer Preview</button>
<button class="btn btn-warning col-md-1" type="reset">Reset</button>
<a href="#">
<button class="btn btn-danger col-md-1" type="button">Cancel</button>
</a>
</div>
</form>
//The code structure I tried
if(isset($_POST['add'])){
$check = $_POST['check'];
$quantity = implode(',', $_POST['quantity']);
$totalprice = implode(',', $_POST['totalprice']);
if (!empty($check)) {
foreach ($check as $chk => $value){
// I printed it for testing.
echo $value.' - product id in the checked checkbox<br>';
print_r($quantity);
print_r($totalprice);
}
}
}
How does this code work the way I want?

Send multiple data using checkbox via ajax

I have created a form which contains a table, the purpose of this is table is to select the desired fees to manage
<form method="POST" action="manage_fees.php" id="manage_form">
<table class="table table-striped table-bordered table-hover" id="table">
<thead>
<tr class="p-4">
<th scope="col">Select</th>
<th scope="col">School fees</th>
<th scope="col">Amount</th>
<th scope="col">type</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input check_amount" name="local_fees">
<label class="custom-control-label" for="check_amount"></label>
</div>
</td>
<td name="selected_fees">Local fees</td>
<td name="amount">200</td>
<td>University fees</td>
</tr>
</tbody>
</table>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="submit">Create</button>
</div>
</form>
Now I want to record it all data("fee name and total payment") that has checked in checkbox table and save in database using ajax.
Once the fees is selected it will display on the on input just like this
<div class="form-group">
label for="fs">Fees selected</label>
<input type="text" class="form-control" id="fs" name="fs" required disabled>
</div>
<div class="form-group">
<label for="tp">Total payment</label>
<input type="number" class="form-control" id="tp" name="tp" required disabled>
</div>
Now, the problem is that im having trouble saving the data that has been checked in table seems there is no data that has been pass in the input.
Sumbit.php
if(isset($_POST['submit'])){
$fs = $_POST['fs'];
$tp = $_POST['tp'];
$result = $connect->query("INSERT INTO manage_fees (fs,tp) VALUES ('$fs','$tp')") or die($connect->error());
}
Instead of this way how will send the data using ajax?

save value of a fallible table in laravel

how do i save the value of my fallible table into my database using loop in laravel 5.5.
CONTROLLER:
public function store(Request $request)
{
$this->validate($request, [
'student_name'=>'required|max:50|unique:leads,student_name',
'gender'=>'required|max:50',
'age'=>'required|max:2',
]);
$leads=new Lead();
$leads->student_name = $request->student_name;
$leads->gender = $request->gender;
$leads->age = $request->age;
$leads->save();
//Display a successful message upon save
return redirect()->route('leads.create')
->with('flash_message', 'Success.');
}
CREATE.BLADE
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='student_name"+i+"' type='text' placeholder='Name' class='form-control input-md' /> </td><td><input name='gender"+i+"' type='text' placeholder='gender' class='form-control input-md'></td><td><input name='age"+i+"' type='text' placeholder='age' class='form-control input-md'></td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
StudentName
</th>
<th class="text-center">
Gender
</th>
<th class="text-center">
Age
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input type="text" name='student_name' placeholder='StudentName' class="form-control"/>
</td>
<td>
<input type="text" name='gender' placeholder='Gender' class="form-control"/>
</td>
<td>
<input type="text" name='age' placeholder='AGE' class="form-control"/>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
I want to save all value in one time is it possible? ...........................................................................................................................................................
You need to send an array to your controller because at the moment your not posting anything to the controller. Even of you were it would have no idea how much it's recieveing and how to receive it.
For example one request could have student_name1 ->
student_name20 or it could only have student_name1 ->
student_name2
If you name the input student_name[]
You can then iterate through the request in your controller, a simple example would be:
foreach ($request->student_name as $student){
Lead::create ([
'name' => $student
]);
}
Hope that helps.

Update data in table row [PHP]

I have a standard HTML table, each row in the table is generated from a database table using a loop.
At the end of each row I have an update button, I'd like this to update data in the table fields.
The image below shows the concept.
The table itself
<div class="container" id="users">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<form method="post" action="">
<table class="table table-bordered table-hover table-striped tablesorter">
<thead>
<tr>
<th width="10%" style="text-align:left">Forename</th>
<th width="15%" style="text-align:left">Surname</th>
<th width="35%" style="text-align:left">Email</th>
<th width="30%" style="text-align:left">Permissions</th>
<th width="5%" style="text-align:left">Update</th>
<th width="5%" style="text-align:left">Delete</th>
</tr>
</thead>
<tbody>
<tr>
<!--here showing results in the table -->
<?php
$adminquery = "SELECT * FROM admin ORDER by user_id DESC";
$IDlist = mysqli_query($dbconEDB, $adminquery);
while($rowlist=mysqli_fetch_array($IDlist))//while look to fetch the result and store in a array $row.
{
$user_id = $rowlist["user_id"];
$admin_email = $rowlist["admin_email"];
$forename = $rowlist["forename"];
$surname = $rowlist["surname"];
$JPortal = $rowlist["JPortal"];
$Tenders = $rowlist["Tenders"];
$News= $rowlist["News"];
$Events = $rowlist["Events"];
$Users= $rowlist["Users="] ;
?>
<td style="text-align:left">
<div class="form-group">
<input name="user_id" id="user_id" type="text" class="form-control" value="<?php echo $user_id;?>">
<input name="forename" id="forename" type="text" class="form-control" value="<?php echo $forename;?>">
<div class="hidden"> <?php echo $forename;?></div>
</div>
</td>
<td style="text-align:left">
<div class="form-group">
<input name="forename" id="surname" type="text" class="form-control" value="<?php echo $surname;?>">
<div class="hidden"> <?php echo $surname;?></div>
</div>
</td>
<td style="text-align:center">
<div class="form-group">
<input name="admin_email" id="admin_email" type="text" class="form-control" value="<?php echo $admin_email;?>">
<div class="hidden"> <?php echo $admin_email;?></div>
</div>
</td>
<td style="text-align:center">
<label>
<input name="JPortal" type="checkbox" id="JPortal" value="1" <?php if ($JPortal == 1) echo "checked='checked'" ;?>> Jobs
</label>
<label>
<input type="checkbox" name="Tenders" value="1" id="Tenders" <?php if ($Tenders == 1) echo "checked='checked'" ;?>> News
</label>
<label>
<input type="checkbox" name="News" value="1" id="News" <?php if ($News == 1) echo "checked='checked'" ;?>> Tenders
</label>
<label>
<input type="checkbox" name="Events" value="1" id="Events" <?php if ($Events == 1) echo "checked='checked'" ;?>> Events
</label>
<label>
<input type="checkbox" name="Users" value="1" id="Users" <?php if ($Users == 1) echo "checked='checked'" ;?>> Users
</label>
</td>
<td style="text-align:center">
<input class="btn btn-newable " type="submit" value="Update" name="EDBsubmit">
</td>
<td style="text-align:center">
<button class="btn btn-newable">update2</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</form>
</div>
</div>
</div>
I'm thinking I've just had an off day and could of in fact wrapped the form around each row of the table.
An easy way to do this is to have a form in each TD containing the update button.
Just make this button a input[type=submit], then add a input[type=hidden] in this form containing the ID of you line row. Then, you could basically get the ID in $_POST.
Example :
<td class="actions">
<form method="post">
<input type="hidden" name="row_id" value="<?php echo $line['id']; ?>"/>
<input type="submit" value="Update"/>
</form>
</td>

Saving a multidimensional array into a mysql database

I am working on a online time tracking web page. But i am stuck at the part on transferring the data into the database.
<?php
/* This loop will iterate through all days. */
foreach($_POST["startTime"] as $day=>$startTimes){
/* This loop will give start & end times for a particular day, i.e. $day */
foreach($startTimes as $timeIndex=>$startTime){
$endTime = $_POST["endTime"][$day][$timeIndex];
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$sql = "INSERT INTO timetableschedule (name, day, startTime, endTime) ".
"VALUES ('$name', '$day', '$startTime', '![enter image description here][1]$endTime')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
}
}
?>
The form looks like this,
<table id="dataTable" class="form-control">
<label for="Monday">Monday</label>
<input type="button" value="Add Schedule" onClick="addRow('dataTable')" />
<tbody>
<tr>
<p>
<td>
<label>Start Time</label>
<input type="text" class="form-control" name="startTime[1][]">
</td>
<td>
<label>End Time</label>
<input type="text" class="form-control" name="endTime[1][]">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="form-group">
<div class="col-sm-7">
<table id="dataTable1" class="form-control">
<label for="Monday">Tuesday</label>
<input type="button" value="Add Schedule" onClick="addRow('dataTable1')" />
<tbody>
<tr>
<p>
<td>
<label>Start Time</label>
<input type="text" class="form-control" name="startTime[2][]">
</td>
<td>
<label>End Time</label>
<input type="text" class="form-control" name="endTime[2][]">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="form-group">
<div class="col-sm-7">
<table id="dataTable2" class="form-control">
<label for="Monday">Wednesday</label>
<input type="button" value="Add Schedule" onClick="addRow('dataTable2')" />
<tbody>
<tr>
<p>
<td>
<label>Start Time</label>
<input type="text" class="form-control" name="startTime[3][]">
</td>
<td>
<label>End Time</label>
<input type="text" class="form-control" name="endTime[3][]">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="form-group">
<div class="col-sm-7">
<table id="dataTable3" class="form-control">
<label for="Monday">Thursday</label>
<input type="button" value="Add Schedule" onClick="addRow('dataTable3')" />
<tbody>
<tr>
<p>
<td>
<label>Start Time</label>
<input type="text" class="form-control" name="startTime[4][]">
</td>
<td>
<label>End Time</label>
<input type="text" class="form-control" name="endTime[4][]">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="form-group">
<div class="col-sm-7">
<table id="dataTable4" class="form-control">
<label for="Monday">Friday</label>
<input type="button" value="Add Schedule" onClick="addRow('dataTable4')" />
<tbody>
<tr>
<p>
<td>
<label>Start Time</label>
<input type="text" class="form-control" name="startTime[5][]">
</td>
<td>
<label>End Time</label>
<input type="text" class="form-control" name="endTime[5][]">
</td>
</tr>
</tbody>
</table>
The database should look like this,
But the only the first row of data managed to enter the database. I am not sure where when wrong with my php codes.
Change your html to this
<td>
<label>Start Time</label>
<input type="text" class="form-control" name="time[0]['start']">
</td>
<td>
<label>End Time</label>
<input type="text" class="form-control" name="time[0]['end']">
</td>
Rest indices will be
time[1]['start']
time[1]['end']
and so on
Then your php code will be easier to read
foreach($_POST['time'] as $day => $time) {
$sql = "INSERT INTO timetableschedule (name, day, startTime, endTime) ".
"VALUES ('$name', '$day', '" . $time['start'] . "', '" . $time['end'] . "')";
}

Categories