PHP: Update database with checkbox values for each row - php

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;
}}?>

Related

anchor tag to call pop up Modal Box without bootstrap not working?

I have a table with each row has link of tag "click here", I want to use a modal box to pop up when a user click on the link and display all row information and allow user to make edit and update.
I am using AJAX with JQuery to pass row id, which is used at backend with PHP to execute SQL Query.
But i don't want to use Bootstrap Modal Box. Please help in making a modal box pop up or something other so that user can make edits on each row of displayed table when a user click on <td><p><a href='' id='%d' value='%d'>Click here</a></p></td>.
I am not clear with how to use Modal Box for each row. may be that could be easier using Jquery.
Below is code of <section> tag of my Dashboard.html which has table.
Here focus on <td><p><a href='' id='%d' value='%d'>Click here</a></p></td>. which include button to call modal box.
<!-- View All Added Campaign and Lead information -->
<section class="operation" id="view_all_lead_Campaign" style="width: 100%;margin: 0 auto; display: none;">
<!-- Main Tables Campaign and Lead Table -->
<div class="row">
<!-- MAIN TABLE-->
<div class="col" >
<button class="viewMainTable" name='viewMainTable' onclick='viewMainTable();' id='viewMainTableButton' >Lead Table</button>
<button class="viewCampaignTable" name='viewCampaignTable' onclick='viewCampaignTable();' id='viewCampaignTableButton' >View Campaign Table</button>
<div class="row">
<div class="col span-4-of-4">
<div style="overflow-x:auto;">
<table class="display_table" id='main_lead_table' style="display: none;">
<thead>
<th>#</th>
<th>Lead Id</th>
<th>Name</th>
<th>Website</th>
<th>Linkedin</th>
<th>Lead Description</th>
<th>Owner Notes</th>
<th>Last Contact Date</th>
<th>Next Contact Date</th>
<th>Lead Status</th>
<th>Details</th>
</thead>
<tbody id='leadTable'>
<?php
function getLeadAddedByName($id){
include('./server/connection.php');
$selectSQL = "SELECT UserName FROM `tbl_user_signup_info` WHERE User_Id = '$id' ";
$result = $conn -> query ($selectSQL);
$name = "";
while($row = mysqli_fetch_array($result)){
$name = $row['UserName'];
}
return $name;
}
include('./server/connection.php');
$selectSQL = "SELECT * FROM `tbl_main_lead_info` ORDER BY Lead_Id";
$result = $conn -> query ($selectSQL);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
printf( "<tr class='content'>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><p><a href='' id='%d' value='%d'>Click here</a></p></td>
</tr>",
$i,
$row['Lead_Id'],
$row['FirstName']." ".$row['LastName'],
$row['Website'],
$row['Linkedin'],
$row['LeadDescription'],
$row['OwnerNotes'],
$row['AdminNotes'],
getLeadAddedByName($row['LeadAddedBy'])."<br>Date/Time: ".$row['LeadAddedOn'],
date('d-m-Y', strtotime($row['LastContactDate'])),
date('d-m-Y', strtotime($row['NextContactDate'])),
$row['LeadStatus'],
$row['Lead_Id'],
$row['Lead_Id'],
);
$i = $i+1;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
Modal.js file to get the click here id and correspoding that PHP at backend execute to fetch record and populate in Modal Box Pop up.
$(document).ready(function() {
$('[name="leadidclick"]').click(function(e){
e.preventDefault();
var leadid = $('[name="leadidclick"]').val();
$.ajax({
type: "POST",
url: './server/modal.php',
data: {
'leadid': leadid
},
success: function(data){
var result = $.parseJSON(data);
console.log(result);
//Modal Box to POP UP HERE
}
});
});
});
My Modal.php file for backend
<?php
// send a JSON encoded array to client
include('./server/connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
if( $_POST['campaignid'] != "" ) {
// echo "Modal.php file is executed";
$id = $_POST['campaignid'];
$selectSQL = "SELECT * FROM `tbl_main_lead_info` WHERE Lead_Id = '$id' ";
$result_array = array();
$result = $conn -> query ($selectSQL);
// If there are results from database push to result array
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
}else{
echo $conn->error;
}
Step 1:
Add a Modal in the page.
Step 2:
Upon click of the anchor element pass the id to ajax function and fetch record
Step 3:
create the form at either php or jquery side.
and show modal with the final response.
At PHP
response from server will have form ready with data, you just need to add the response to modal-body div.
$.ajax({
url :: 'your url',
type : 'post',
data : {id: row id},
success: function(response){
$('.modal-body').html(response);
$('#your-modal-id').modal('show');
}
});
At Jquery side
$.ajax({
url :: 'your url',
type : 'post',
data : {id: row id},
dataType: "JSON",
success: function(response){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#form-element').val(json[i].item_name);
.
.
.
}
$('#your-modal-id').modal('show');
}
});
Please note: there are many ways to do it, if you find it complex, feel free to write, I will try to give you exact solution. :)

php insert button value for user

i have a table where i print out all of the users for the program. now i would like to have a toggle Bootstrap button for Activate and Incative. I would like to store 1 and 0 into my database. how do i save the value for the specific User ID the value and then update it when the button pressed. Also how to then when it has been pressed to then update the page? is it possible to not refresh the page?
<div class="table-responsive-sm">
<table class="table table-bordered table-condensed table-striped text-center table-dark">
<tr>
<th> First Name</th>
<th>Last Name</th>
<th>E-mail</th>
<th>Username</th>
<th>Accreditation</th>
<th>Instructor ID</th>
<th>Time Registered</th>
<th>Account State</th>
<th>Activate</th>
<th>SET Inactive</th>
</tr>
<?php
$sql = ("SELECT * FROM instructors GROUP BY ID ORDER BY ID DESC ");
$result=mysqli_query($mysqli,$sql);
while ($row=mysqli_fetch_array($result)){
$accred = $row['role'];
if($accred == '0'){
$test = 'Admin';
} else if ($accred == '1') {
$test = 'Bookkeper';
} else if ($accred == '2') {
$test = 'Coordinator';
} else if ($accred == '3') {
$test = 'Instructor';
}
$LoginState = $row['LoginState'];
if($LoginState == '0'){
$LogState = '<td style="color: White; background-color: orangered"><b>Inactive</b></td>';
} else if ($LoginState == '1') {
$LogState = '<td style="color: black; background-color: lightgreen"><b>Active</b></td>';
}
$ID = $row['ID' ];
echo "
<form method=\"POST\">
<tr>
<td>".$row['Fname']."</td>
<td>".$row['Lname']."</td>
<td>".$row['Email']."</td>
<td>".$row['username']."</td>
<td>".$test ."</td>
<td>".$row['ID' ] ."</td>
<td>".$row['RegisteredTime']."</td>
$LogState
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-success\" role=\"button\" value\"1\">Activate</button</td>
<td><button name=\"LoginState\" type=\"button\" class=\"btn btn-warning\" role=\"button\" value\"0\">SET Inactive</button</td>
</tr></form>";
}
if (isset($_POST['LoginState'])){
$sql1 = "INSERT into instructors (LoginState) VALUES ($logstats) WHERE ID = $ID";
if ($mysqli->query($sql1) === TRUE) {
echo "New record created successfully";
echo "<br/>";
} else {
echo "Error: " . $sql1 . "<br>" . $mysqli->error;
}}
Here is the html code to show toggle button
<td data-title="Status">
<label class="switch">
<input type="checkbox" id="toggle<?php echo $id; ?>" name="status_<?php echo $id; ?>" <?php if($status == 'on'){echo "checked"; }?> >
<div class="toggle round"></div>
</label>
</td>
$id is dynamic id which you get from db.you need proper CSS these classes to make it toggle button.
AJAX call to update records in db onChange of checkbox value
<script type="text/javascript">
$(document).ready(function(){
$('#toggle<?php echo $id; ?>').click(function(){
var id = <?php echo $id; ?>;
if($(this).prop("checked") == true){
var stat = 'on';
}
else if($(this).prop("checked") == false){
var stat = 'off';
}
$.ajax({
type: "POST",
url : "example.php",
data : { id : id,stat :stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
});
});
</script>
$id is same as above. You need to do update then select query in example.php to update content in page, without refreshing the page
Mark, as others said, if you want to refresh part of your page without reloading the whole page, you need to use AJAX.
One of the most popular and simple way to use AJAX is including the jQuery.js library. If you already use javascript, you will find a bit easy to include jQuery in your page. (you can find and copy the jquery.js file anywhere on internet, just type "download jquery file" in google)
in example, you can put this code in your html (in fact, you can put it almost in any place of your page)
<script type="text/javascript" src="jquery.min.js"></script>
Then you can use the softech's example...
<script type="text/javascript">
$(document).ready(function(){
...
$.ajax({
type: "POST",
url : "PageThatOnlyReturnsData.php",
data : { id:id, stat:stat },
success: function(data) {
//update value in page acc to new updated value from db
}
});
...
});
</script>
It's strongly recommended thay you create another php page to place de mySQL code and returns data (I named in example "PageThatOnlyReturnsData.php"), so this php page will print out the result data from your query.
So, the front php (the first page with HTML) calls the second php (the data php) through the $.ajax() function, and you can process the received data within the "success" function.
success: function(data) {
//here "data" is what you receive from the second php
//do what you want here with javascript using the new variable "data" as in the softech's example
}

Ajax / Php sending id from while loop on click to view record details

i have a table with differente IDs on each row (obtained from a while loop), and next to each ID i have element to view the details of this specific record. Now i understand if i want to retrieve the id, i have to send via post method in a form, but i don't want the page to refresh because i'm using bootstrap tabs, i don't want the page to go back to the first tab, therefore, i'm trying to use Ajax not to make the page refresh.
So first of all i have my first table :
I am in Medical Records Tab > Member Medical Records.
and my View item is :
<td style='text-align:center;'> <ul class='nav nav-tabs'><form><a data-toggle='tab' id='testz' value='".$rowmed[0]."' href='#viewMed' role='button'></form><i style='color: gray;' class='fa fa-eye'></i></a></td></ul>
Now i write an ajax script with the variable recdetailsid in DATA:
<script>
$("#testz").click(function(e) {
switchVisible();
e.preventDefault();
$(this).toggleClass( "selected" );
$.ajax({
type: "POST",
data: {
recdetailsid: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing Details !');
},
error: function(result) {
alert('error');
}
});
});
`
and then to get this ajax element :
if ($_SERVER['REQUEST_METHOD'] == 'POST' ) {
if(isset($_POST['recdetailsid'])){
$recdetailsid=$_POST['recdetailsid'];
$sqlmedr = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Created 2 same queries with different names because can't fetch_array twice on the same query and need to pull data twice, 1 outside the while and 1 in a while for table results
$sqlmedrx = "Select Record_id,Medical_Condition,Date,Notes FROM medicalrecords,teachers WHERE Teacher_id=".$comid." and medicalrecords.CommonID=teachers.CommonID and Dependant_id IS NULL and Record_id=".$recdetailsid." ";
// Record_id need to be sent on view click !!!!!!!!!!!! now it is specified explicitely
$resultmedr = $conn->query($sqlmedr);
$resultmedrx = $conn->query($sqlmedrx);
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important;">
<h3 style="color:black;">Member Record</h3></div>
<?php
$rowmedrx = mysqli_fetch_array($resultmedrx);
if ($type=='teachers') {
echo "Record Id: <td>".$rowmedrx['Record_id']."</td> ";
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "Notes : <td>".$rowmedrx['Notes']."</td> ";
} else {
$sqlmedr = "Select DISTINCT Record_id,Medical_Condition,Date FROM medicalrecords,teachers,dependants WHERE medicalrecords.Dependant_id=".$comid." and medicalrecords.Dependant_id=dependants.Dependant_id ";
$resultmedr = $conn->query($sqlmedr);
echo "<table class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th>Condition</th>
<th>Date Of Diagnosis</th>
</tr>
</thead>";
while ($rowmedr = mysqli_fetch_array($resultmedr)) {
echo "<tr>
<td>".$rowmedr['Medical_Condition']."</td>
<td>".$rowmedr['Date']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
}
} }
?>
<div class="jumbotron" style="margin-top: 20px; padding-left:0px !important; ">
<h3 style="color:black;">Documents</h3></div>
But everything in the server $_POST brackets and isset $_POST brackets does not show, only the alert shows with the Document jumbotron.
( you can see i'm using the variable inside the query, Record_id=".$recdetailsid." ) , this is my whole purpose !
Can anyone give me some tips or help please ? i'm new to ajax but trying my best to get through this, appreciated!

How to insert form input field in table?

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. :(

Dynamically update the table on selecting checkbox

I'm very new to php and have been given the task to update the table in the database when user select the check box and then edit the information in the text box. I'm able to pull the information from database and display it on the screen, however I'm not too sure how to update the database when user selects the checkbox and update the field
Here is what I want to achieve:
1) On clicking the checkbox, the row gets editable.
2) After updating the field value, and clicking button "update", the value gets updated in the d/b
<div class="table-responsive">
<table class="table table-condensed">
<thead>
<tr>
<th width="20%">Field Name</th>
<th width="52%">Field Text</th>
<th width="32%">Select to Update</th>
</tr>
</thead>
<tbody>
<?php
if($table = true)
{
while($row = $result->fetch_assoc())
{
$fieldName[] = $row['fieldName'];
$fieldText[] = $row['fieldText'];
$fieldID[] = $row['ID'];
echo "<tr>";
echo "<td>".$row['fieldName']."</td>";
echo "<td>".$row['fieldText']."</td>";
echo "<td>"."<input type= 'checkbox' value='{$row['ID']}', name = ID[]>"."</td>";
echo "</tr>";
}
}
else
{echo "No results found";}
?>
</table>
</div>
Not sure how to proceed further. After checking forums, I found that Jquery is the way to go, but not sure how to make the field updatable.
Please note that I haven't provided the code for the "Update" functionality.
Sorry, i am not good in jquery. But i think for this u could use
$('.your-check-box').on('change', function() {
if(this.checked)
{
//change text on inputs
}
else {
//change inputs on text
}
});
this is quick example:
http://jsfiddle.net/qr4ova98/
For DB update u need to send ajax with data on event.

Categories