How to insert form input field in table? - php

I have displayed all the student's name in table format through ajax. Now I want to associate a form input field to each student so that I can insert his marks and store it in database? How can I achieve this?
Below is my code..
<script type="text/javascript">
function select_std() {
var ali = $('#class_std').val();
$('#std_name').html('');
$.ajax({
url: "<?php echo base_url().'admin/test/'?>" + ali,
type: "GET",
success: function(res) {
$('#myTable tbody').append(res);
}
});
}
</script>
and my controller :
public function test($id=''){
$table='students';
$columns=array('*');
$where=array('c_id'=>$id);
$data['rcd']= $this->Crud->get_records($table, $columns, $where)->result();
foreach ($data['rcd'] as $value) {
$output = "<tr><td>".$value->Name."</td><td>90</td><td>very good<td></tr>";
echo $output;
}
}
This is my table format in which I have showed all the student's names in the first <td> through ajax from database. and I want to make the second <td> as input field to store his marks in database.
<table cellpadding="1" cellspacing="1" id="myTable" class="table table-boardered table-responsive" id="example2">
<thead>
<th width="20px;">Name</th>
<th>Marks obtained(100)</th>
<th>comments</th>
</thead>
<tbody id="std_name">
</tbody>
</table>

You should put a form on the table/your loop so that every student has a designated input field then if you want to make an action to a specific student get the ID of the specific student then inserts it to the DB. (get(id) = idfromdb).
<?php foreach ($data['rcd'] as $value) { ?>
<tr><td><?php $value->Name ?></td><td>90</td><td>very good<td></tr>
<tr><td>
<input field here>
<input button value=$value[id]>
</td></tr> <?php } ?>
then in the next page or the same page its up to you:
<?php if(isset($_POST['button name'])){
$id = $_POST[button name];
insert your data to your db where $id = idfromdb }?>
ahaha sorry dude I forgot php. :(

Related

PHP: Update database with checkbox values for each row

I'm currently working on displaying a table containing a list of alarms, where each row contains a checkbox that determines whether the user has already viewed that alarm or not. Here's
an image:
So far, I managed to check/uncheck the checkbox given its state in the database. What I want to do, and don't exactly know how to, allow the user to check/uncheck a checkbox and immediately update the database with this new state without pressing a submit button. The code that I have right now is the following.
<div class="card-body table-responsive p-0">
<form action=modules/alarms.php method="POST">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Tipus</th>
<th>Data</th>
<th>Vista</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result->fetchAll() as $row){
if ($row[4] == 1){
$status = "checked";
}else{
$status = "";
}
echo
'<tr data-widget="expandable-table" aria-expanded="false">
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
<td><input type="checkbox" name="chk1[]" value="viewed" '.$status.'></td>
</tr>
<tr class="expandable-body">
<td colspan="5">
<p>
<video width="416" height="416" controls>
<!-- el 42 es la cabecera C:/... fins videos-->
<source src="'.substr($row[3], 42).'" type="video/mp4">
Your browser does not support the video tag.
</video>
</p>
</td>
</tr>';
}
?>
</tbody>
</table>
And the PHP code I have (I don't have the code that will update values on the database, but I'll figure that out. I want to know how I could retrieve the value of the checkbox of every row and its ID so I can update it on the database.
$ei = $_POST['chk1'];
if ($_POST["chk1"] == "chk1") {
for ($i = 0; $i < sizeof($checkbox1); $i++) {
print_r($checkboxl[$i]);
}
}
To solve this problem, first I had to add some fields to the checkbox input. WIth those changes, the table is generated as it follows:
<tr data-widget="expandable-table" aria-expanded="false">
<td>'.$row[0].'</td>
<td>'.$row[1].'</td>
<td>'.$row[2].'</td>
<td><input type="checkbox" name="id" id="viewed" value="'.$row[0].'" '.$status.'></td>
</tr>
After this is done, simply add a script that will retrieve the values from the clicked checkbox and pass them to the necessary PHP function:
$("input").change(function() {
if ($(this).is(':checked')){
var viewed=1;
}else{
var viewed = 0;
}
var id = $(this).val();
$.ajax({
url:"modules/alarms.php",
method:"POST",
data:{viewed:viewed,id:id,},
success: function(data){
},
});
Please note that the 'url' field is the relative path where our PHP function is implemented.
And now, simply update the database with the checkbox value (I'm using PDO objects) as it follows:
<?php
if(isset($_POST["viewed"])) {
$id = $_POST["id"];
$viewed = $_POST["viewed"];
$sql="UPDATE `alarms` SET `viewed` = '$viewed' WHERE (`id` = '$id')";
if($connection->query($sql) === TRUE){
echo "Success";
} else {
echo "error" . $sql . "<br>".$connection->error;
}}?>

Edit particular field in a row of the table and update edited value in MySQL table

I am fetching data from database in a table.Now i want to edit particular field in a row of the table and save that value into MySQL.
This is my complete code for displaying data in table and editing. Here i want to edit the status. It is editable but after editing how to get the value from the table and update that value to MySQL.
<?php
include "config.php";
$sql = "select * from d_jobs where Status ='drafted' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
//echo $count;
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$("document").ready(function(){
$('#sdata').click(function(){
var myTxt = $(('.status')+[i]).html();
console.log(myTxt);
var id = $(('.status')+[i]).attr('id');
console.log(id);
}
/* $.ajax({
type: 'post',
url: 'job_field_edit.php',
data: 'varname=' +myTxt
}); */
});
});
</script>
</head>
<body>
<table border="2" align="center">
<thead>
<tr>
<th>Job Name</th>
<th>Builder</th>
<th>Job Type</th>
<th>Status</th>
<th>Effective Date Start</th>
<th>Estimated completion date</th>
<th>Job Gal Glag</th>
<th>Take List Flag</th>
<th>Planner</th>
<th>Project Manager</th>
<th>Hand Over</th>
<th>Other Comments</th>
</tr>
</thead>
<tbody>
<?php
if( $count ==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_array($result)){
echo "<tr><td>{$row['JOB_NAME']}</td>
<td>{$row['BUILDER']}</td>
<td>{$row['JOB_TYPE']}</td>
<td contenteditable='true' id='{$row['JOB_ID']}' class='status[{$row['JOB_ID']}]'>{$row['status']}</td>
<td>{$row['EFFECTIVE_START_DATE']}</td>
<td>{$row['ESTIMATED_COMPLETION_DATE']}</td>
<td>{$row['JOB_GAL_FLAG']}</td>
<td>{$row['JOB_TAKE_LIST_FLAG']}</td>
<td>{$row['Planner']}</td>
<td>{$row['Project_Manager']}</td>
<td>{$row['Handover']}</td>
<td>{$row['Comments']}</td>
<td><input name='need_delete[{$row['JOB_ID']}]' type='checkbox' id='checkbox[{$row['JOB_ID']}]' value='{$row['JOB_ID']}'></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<input id="sdata" type="button" value="Send Data" />
</body>
</html>
<?php
mysqli_close($conn);
?>
There's a number of ways to approach this. One is to dispense with the manual Send Data button and allow javascript to respond automatically to users' contenteditable edits.
Unfortunately, contenteditable elements don't fire a change event but they do fire a blur event, from which a change event can be triggered.
First, build your contenteditable elements like this :
<td contenteditable=\"true\" class=\"status\" data-job-id=\"{$row['JOB_ID']}\">{$row['status']}</td>
Then, for each contenteditable element, attach a blur handler, and initialize a data-value attribute equal to innerText.
$('[contenteditable]').on('blur', function(e) {
var self = $(this);
if(self.text() !== self.data('value')) {
self.trigger('change');
}
self.data('value', self.text());
}).each(function() {
$(this).data('value', $(this).text()); // equivaluent to data-value="{$row['status']}".
});
Thus you can have contenteditable elements that mimic, at least in part, HTML input elements.
So now you can attach a change handler as you would for a standard HTML input element.
$(".status").on('change', function(e) {
var job_id = $(this).data('jobId');
var old value = $(this).data('value');
var current value = $(this).text(); // in this regard, <input> is not mimicked. For a genuine <input> we would write `$(this).val()`.
// here, perform ajax to keep server-side up to date.
});
DEMO
Note: This approach is slightly over-the-top when [contenteditable] and .status are virtual synonyms for each other. However, in the general case where there might be several different classes of contenteditable element, then you would likely avoid much repetition of code.

CodeIgniter Delete row from datatables involving mysql database

Hi I am wondering if it's possible to do something like selecting a row within a datatable and have a button "delete" with a method in the controller.
My delete button is to remove the row from the database itself and refresh the page.
This is what my view contains:
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#datatables').DataTable();
});
</script>
<table id= "datatables" class = "table">
<thead>
<tr>
<th> Patient Name </th>
<th> Patient`enter code here` ID </th>
</tr>
</thead>
<tbody class = "list">
<?php foreach ($patients as $patient): ?>
<tr>
<td><?=$patient->first_name ?></td>
<td><?=$patient->patientID ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
(delete button)
echo anchor('something/delete', 'Delete', 'class= "some class"');
What i want to do is:
Get the id of the selected row in the datatable and pass it to another page in a controller for processing.
Is that possible?
since you are using DataTables plugin. when defining your columns, add a column for checkboxes, like so:
{
"data": null,
"defaultContent": "",
'class':'user_chkbox',
"searchable": false,
"render": function ( data, type, full, meta ) {
var checkbox = "<input type='checkbox' name='user_ids[]' value='" + data.id + "' />";
return checkbox ;
}
},
you can get the list of id's to delete by accessing the 'user_ids' post data.
$user_ids = $this->input->post('user_ids');
you can then in your submit handler function:
$this->db->where_in('id',$user_ids);
$this->db->delete('user_table');

yii add more textbox not saved in database

In my view the form as
<table width="90%" border="0" cellspacing="2" cellpadding="2" id="table-data" align="center" style="border:1px dashed #CCCCCC" class="table table-vcenter table-striped">
<tr class="tr_clone">
<td> % Completion</td>
<td> <?php echo $form->textField($model_result,'floatPaymentpercentage[]',array('class'=>'form-control','placeholder'=>'%')); ?></td>
<td> <?php echo $form->textField($model_result,'varAmount[]',array('class'=>'form-control','placeholder'=>'Amount')); ?></td>
<td><input type="button" name="add" value="Add" class="tr_clone_add btn btn-xs btn-warning"></td>
</tr>
Here i have two textboxes for payment terms..if i save ones it will be saved.
If i add more the last will not saved in database
In my controller we can use print_r()
echo ("<pre>"); print_r($_POST); echo ("</pre>");exit;
The default text field values only shown here.
Here the text fields are added dynamically.
The dynamic added text field's values are not displayed.
In my model the rules are
public function rules()
{
return array(
array('floatPaymentpercentage','required'),
array('varAmount','required'),
);
}
here is the java script for add more
<script type="text/javascript">
$(document).on('click','.delete',function(){
$(this).closest('tr').remove();
});
$("input.tr_clone_add").live('click', function() {
if($(this).val() == "Add")
{
var $tr = $(this).closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.find('.tr_clone_add').val('Delete')// set value to Delet
$tr.find('.tr_clone_add').val('Delete')// set value to Delet
.toggleClass('tr_clone_add delete')// toggle classes
.unbind('click'); // unbind the current events from button
$tr.after($clone);
}
else
{
$(this).closest('tr').remove();
}
});
</script>
Please help me to fix this.
Here i can add js for funuction add more
Thanks

Making of new record and showing it inside a div (append to a while loop)

I'm trying to to make a form that will submit a new record and automatically show that as DIV inside of the main DIV and after all the results from the PHP while loop.
Here is the while loop that I've built:
<?php
while ($row_apps = mysql_fetch_array($result_apps))
{
if ( ($row_apps['type'] == 'ar') && ($row_apps['client'] == NULL) ) {
echo '<center>
<div id="_'.$row_apps['app_id'].'" class="tab_listing">
<table width="248" border="0" cellspacing="10px" cellpadding="0px">
<tr>
<td width="100%" colspan="3"><div class="tab_listing_header">'.$row_apps['app_name'].'</div></td>
</tr>
<tr>
<td class="tab_listing_values"><b>App ID: </b>'.$row_apps['app_id'].'</td>
<td class="tab_listing_values"><b>Users: </b>'.$row_apps['users'].'</td>
</tr>
</table>
<div id="edit">Edit</div>
<div id="delete"></div>
</div>
</center><br>';
}
}
?>
Now basically what i need to do is when a form is submitted and the new record is in the database i want it to show a new "block" exact same like the while "blocks" live.
I was thinking about something like:
$.post("create.php",{ value1:$('#value1').val(),value2:$('value2').val(),rand:Math.random() } ,function(data)
{
if(data=='yes')
{
HERE I'M STUCK.
Thanks!
Try this
$.post("create.php",{ value1:$('#value1').val(),value2:$('value2').val(),rand:Math.random() } ,function(data)
{
if(data)
{
$("mainDivSelector").html(data);
}
);
data will contain a result string returned by create.php and that is entirely up to you. What does create.php do at the moment?

Categories