Populating form from table row - php

I have added a button at the end of the row of my datatable intended to update the information in the database for the specific row chosen.
When I click the update button, a form pops us with the relevant fields to update.
Ideally, I would like the form to be autopopulated with the information from the table row which I have chosen to update
Code...
Table:
<div class="viewalljob tab-pane show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<h2>Edit Job Table</h2>
<table id="edit-job-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="job_id">ID</th>
<th class="job_date">Date</th>
<th class="job_company">Company Name</th>
<th class="job_contact">Contact</th>
<th class="job_from">From</th>
<th class="job_to">To</th>
<th class="job_driver nowrap">Driver</th>
<th class="job_income">Income (£)</th>
<th class="job_payment">Payment (£)</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--Fetch from Database-->
<!--Connect To Database-->
<?php
$host_name = 'xxx';
$database = 'xxx';
$user_name = 'xxx';
$password = 'xxx';
$conn = mysqli_connect($host_name, $user_name, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT *,AS markup
FROM `table`
GROUP BY id";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<tr>
<td class='job_id'>".$result['id']."</td>
<td class='job_date'>".$result['adddate']."</td>
<td class='job_company'>".$result['customer']."</td>
<td class='job_contact'>".$result['addcontact']."</td>
<td class='nowrap job_from'>".$result['addfrom']."</td>
<td class='nowrap job_to'>".$result['addto']."</td>
<td class='nowrap job_driver'>".$result['adddriver']."</td>
<td class='currency job_income'>".$result['addincome']."</td>
<td class='currency job_payment'>".$result['addpayment']."</td>
<td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td>
<td><button type='button' name='delete' id=".$result['id']." class='btn btn-danger btn-xs delete deletebtn'>Delete</button></td>
</tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<div id="contactForm3">
<h1>Edit Job</h1>
<form id="dataForm" name="dataform" method="POST" action="/">
/**** FORM DATA ****/
</form>
</div>
JS to open form:
$(function() {
// contact form animations
$('.update').click(function() {
$('#contactForm3').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm3");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
I have added the update button using <td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td> I have given the id=".$result['id']." hoping that I can use this to populate the form from the ID
I am assuming that I will need to connect to the database table, something like:
<form>
<?php
//Connect to Database ... //
$sql = SELECT * FROM `table`
WHERE ID = ???
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<span>
<label> label1 </label>
<input value = ".$result['column'].">
</span>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Im hoping that this is correct and someone can help me do this?

Actually you can acheive this using javascript/jquery, get row element from table displayed, from which you can get every columns/inputs value like as below:
$('.updatebtn').on('click', function(e) {
e.preventDefault();
var row = $(this).closest('tr'); //get table row from displayed table.
var form = $('#contactForm3').fimd('form'); //form to be populate.
//make sure your form input field with same name as the column name.
//now create form_data object with key as same name as column/input name .
var form_data = { 'id' : row.find('.job_id').value(),
'adddate' : row.find('.job_date').value(),
.....
'addpayment' : row.find('.job_payment').value()
}
//Apply loop to populate values in form.
$.each(form_data, function(key, value){
form.find('input[name="'+ key +'"]').val(value);
});
});
Then on form submit update database record/row using PHP (hope you know that well, if not let me know I will update my code).

Related

Auto Incrementing value to be assigned as input then using value to delete item from database;

I am a student with a couple of weeks into PHP. What I am trying to do is Generate A table containing all users messages. Then I need a check box in each row. When the user hits the delete button rows with checkboxes marked will be deleted from table. The issue is that I can not figure out how to assign an individual value to each row of the HTML table to target with PHP. So I will only delete the rows that have been selected. I've only been able to delete all rows.
Here is what I got so far
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
// display table headers
echo '<form>
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</tdclass=center>
<th class="center">Message</th>
<th class="center"> <button type="submit" name="button1">Delete Selected</button</th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
if(isset($_POST['button1'])) {
$sql = "DELETE FROM contacts WHERE id=$field1name";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center"> <input type="checkbox" id="if_checked" name="if_checked"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>
Your code is wrong, you just delete all your data along with your foreach run, so I just want to say keep learn more about programming logic since you're student
ok, for your question you have to put delete query before
$query = "SELECT * FROM contacts";
and your delete query should be based from foreach of checkbox value, and the most important thing is your checkbox name should be an array name since you will post multiple checkbox with the same name
<input type="checkbox" class="if_checked" name="if_checked[]">
and then you can use code like this
..................
include("../partials/.connect.php");
if(isset($_POST['button1'])) {
foreach($_POST['if_checked'] as $id) {
......your delete query
}
}
// select rows from contacts
$query = "SELECT * FROM contacts";
...................
You can use the checkbox as an array where you will store the ids when you select checkboxes for delete, you will loop through checkboxes and will be able to delete all selected rows.
I Was Able to solve this by storing the $row['id'] variable in the checkbox value instead of $Field1name. allowing me to specify which row to delete.
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
//if delete button is set
if(isset($_POST['delete'])) {
$selected = $_POST['if_checked'];
//confirm record target
$confirm = mysqli_query($conn, "SELECT * FROM contacts WHERE id = '$selected'") or die("Not Found");
if(mysqli_num_rows($confirm)>0){
//record found delete
$delete_query = mysqli_query($conn, "DELETE from contacts where id = '$selected'")
or die("Not Deleted");
echo "<div><p>Record Deleted</p></div>";
} else {
//record not DataBase
die("Not deleted".mysqli_error());
}
}
// display table headers
echo '<form method="post" action="" role="form">
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</th>
<th class="center">Message</th>
<th class="center"><input class="center" type="submit" name="delete" value="Delete"></th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center">
<input type="checkbox" id="if_checked" name="if_checked" value="'.$row['id'].'"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>

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

How can i apply the datatable filters to my php code?

I am getting some data and displaying on the table which i have created in my php code however i want to apply the data table filters but i cannot seem to find a solution. I know in html i can assign an id to the table and then call it from a js script using the following code var table = $('#myTable').DataTable({"dom":"ftip"}); however this doesn't seem to work in my code. Perhaps because i am wrapping the html code in php?
Thanks
<script>
$(document).ready(function(){
var table = $('#myTable').DataTable({"dom":"ftip"});
});
</script>
<?php
$conn = mysqli_connect('localhost', 'root', '""', 'calendar');
extract($_POST);
if(isset($_POST['readrecords'])){
$data = '<table class="table table-bordered table-striped" id="myTable">
<tr class="bg-dark text-white">
<th>No.</th>
<th>Title</th>
<th>Driver</th>
<th>Date</th>
</tr>';
$displayquery = "SELECT id,title, driver, start FROM `events` ";
$result = mysqli_query($conn,$displayquery);
if(mysqli_num_rows($result) > 0){
$number = 1;
while ($row = mysqli_fetch_array($result)) {
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['title'].'</td>
<td>'.$row['driver'].'</td>
<td>'.$row['start'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-success">Edit</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
$data .= '</table>';
echo $data;
}
?>
function readRecords(){
var readrecords = "readrecords";
$.ajax({
url:"backend.php",
type:"POST",
data:{readrecords:readrecords},
success:function(data,status){
$('#records_content').html(data);
},
});
}

Load more button works just once

I have a table named tbl_video that consist of two fields (video_id, video_title What I want to add a load more button using Ajax JQuery like social networking sites .I am able to get the first two records but when I try second time nothing happens. I dont get any errors .What am i doing wrong .
this my index.php file I create table structure here and then fetch two records.And get the second record's id value and send it to the more.php file
<body>
<table class="table table-bordered" id="load_data_table">
<thead>
<tr>
<td width="15%">Video Id</td>
<td>Video Title</td>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($result)) {
$video_id = $row['video_id']; ?>
<tr>
<td><?php echo $row['video_id']; ?></td>
<td><?php echo $row['video_title']; ?></td>
</tr>
<?php
}
?>
<tr id="remove_row"><td><button type="button" id="more" class="btn btn-success form-control"
data-id="<?php echo $video_id; ?>">More</button></td></tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#more').click(function(){
var id=$(this).data("id");
$.ajax({
url:"more.php",
data:{id:id},
method:"post",
success:function(data){
if(data!=''){
$('#load_data_table').append(data);
$('#remove_row').remove();
}
else{
$('#more').html("No Data");
}
}
and this the more.php file.I think it is self explanatory
$id = $_POST['id'];
$output = '';
$db = mysqli_connect('localhost', 'root', '', 'testing');
$data = mysqli_query($db, "select * from tbl_video where video_id >{$id} limit 2");
if (mysqli_num_rows($data)) {
while ($row = mysqli_fetch_array($data)) {
$output .= '
<tbody>
<tr>
<td>'.$row['video_id'].'</td>
<td>'.$row['video_title'].'</td>
</tr>
';
}
$output .= '
<tr id="remove_row"><td><button type="button" id="more" class="btn btn-success form-control"
data-id="'.$row['video_id'].'">More</button></td></tr></tbody>
';
echo $output;
}
any help would be appriciated.
When you add a new row and there is a new button for More
It has the same id as the original button so there is a conflict there
also the javascript needs to be initiliazed something like this
PHP:
$output .= '<tr id="remove_row"><td><button type="button" class="more btn btn-success form-control" data-id="'.$row['video_id'].'">More</button></td></tr></tbody>';
Javascript:
<script>
function moreButton() {
$('.more').click(function(){
var id=$(this).data("id");
$.ajax({
url:"more.php",
data:{id:id},
method:"post",
success:function(data){
if(data!=''){
$('#load_data_table').append(data);
$('#remove_row').remove();
moreButton();
}
else{
$('.more:last').html("No Data");
}
}
});
}
$(document).ready(function(){
moreButton();
});
Don't forget to remove the id of the more button to a class with .more

Alert when delete button is pressed is not working

I'm doing Inventory tracking system, and I want there is an alert say "Are you sure?" when the delete button is pressed. It work when you press delete, but the alert not showing up.
This is my code:
<html>
<head>
<title>View Records</title>
</head>
<body>
<p><a href="Search_Vendor.php"><img src="img/SEARCH2.jpg" width="25"
height="27" align='left'></a></p>
<div class="dropdown"><img class="dropbtn" img src="img/dropdown.png"
width="44" height="47"></img>
<div class="dropdown-content">
HOMEPAGE
ADD NEW RECORD
PRINT
</div>
</div>
<center> <h2> VENDOR RECORD </h2> </center>
<?php
// connect to the database
include('connection.php');
// get results from database
$result = mysql_query("SELECT * FROM vendor")
or die(mysql_error());
// display data in table
echo "<table border='1' cellpadding='20' cellspacing='0' align ='center'";
echo "<tr> <th>Vendor ID</th> <th>Vendor Name</th> <th>Contact No </th>
<th>Address</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>
<td align = center>".$row['Vendor_ID']."</th>
<td align = center>".$row['Vendor_Name']."</th>
<td align = center>".$row['Contact_No']."</th>
<td align = center>".$row['Address']."</th>
<td><a href='Update_Vendor.php?ID=$row[ID]
&Vendor_ID=$row[Vendor_ID]
&Vendor_Name=$row[Vendor_Name]
&Contact_No=$row[Contact_No]
&Address=$row[Address]'>Update</a></td>
<td>
<a onclick="return confirm('Are you sure?')"
href="Delete_Vendor.php?ID=<?= $row[ID] ?>">Delete</a>
</td>
</tr>";
}
//close the table
echo "</table>";
?>
</p>
</body>
</html>
Thanks for your help.
Regards
Since you're using a link for you clicked element, it's likely that it is trying to actually open the link address before your code can run. Use e.preventDefault(); with and event handler like below to avoid that behaviour:
See this jsFiddle
<a class="delete" href="Delete_Vendor.php?ID=123">Delete</a>
$(function() {
$('.delete').click(function(e) {
var $this=$(this);
e.preventDefault();
if (confirm('Are you sure?')) {
// code to delete stuff
window.location=$this.attr('href');
}
});
});
I found this example on the net... http://www.w3schools.com/jsref/met_win_confirm.asp
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

Categories