Update row on datatable using ID - javascript

I have a table in an oracle database that I am showing on a web page. I used bootstrap to style my page and dataTables for pagination and search as well as sorting. I want to update any particular row at anytime using the unique ID column(BID), so I have added an update link next to each row using the foreach loop.
My problem now is to get the logic to build that functionality to make the update link. I want to:
Find a way to know which row the user has clicked to update, and retrieve that record/row to a form for update using the ID.
Challenge:
I am using a loop to fill the table and I can't think of a way to link each row ID to the update link by it. I tried filling an array with the ID's but how to connect what update link to what ID for retrieval beats me.
I am using html and PHP as well as some simple javascript. I am not good at javascript and have little knowledge in ajax also. I am yet to learn them but I understand they are the best to use for such things. Perhaps, I am not using the best approach, so if anybody can help me out with a much better one within my scope. Find my code below.
<table class="table table-striped" id="scriptstable">
<thead>
<tr>
<th>Update</th><!--This is where update links are-->
<th>Place</th>
<th>Report Name</th>
<th>Index</th>
<th>Source</th>
<th>Core Field</th>
<th>Description</th>
<th>ID</th>
</tr>
</thead>
<?php
//Connection string is here
$stid = oci_parse($conn, 'SELECT * FROM mytable ORDER BY REPORT_NAME');
oci_execute($stid);
echo "<tbody>";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
echo "<tr>";
echo " <td><a data-toggle='modal' data-target='#myModal' href='#' >Update</a>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
} $bid[]=$row['BID'];//Array that stores ID as they come
echo "</tr>";
}
?>
</tbody>
</table>
UPDATE:
$ajaxAction = $_REQUEST['ajaxaction'];
if (!method_exists('ajaxHandler', $ajaxAction)) {
die("No such action {$ajaxAction}");
}
$handler = new ajaxHandler();
$handler->$ajaxAction();
class ajaxHandler
{
function __construct()
{
//just an empty constructor
}
function updateRow()
{
//Connection
$conn = oci_connect('username', 'password', 'localhost/XE', 'WE8MSWIN1252');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$BID = $_REQUEST['BID'];
$stid = oci_parse($conn, 'SELECT * FROM Bo_repository WHERE BID = {$BID}');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
// echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
echo " <td><a id='{$row['BID']}' href='#' onclick='updateRow(this)'>Update</a></td>";
//header("Location:index.php");
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
}
}
?>

When you emit your rows in the table you can assign the id to the table row... I usually do it concat with row or something... and include the id as the id of your tag. You can then use the onclick to call a javascript function using ajax to update your table row dynamically e.g.
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
echo "<tr id='row_{$row['BID']}'>";
echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
$bid[]=$row['BID'];//not sure this is really needed anymore
echo "</tr>";
}
The updateRow function would be something like this... In a script tag of course...
function updateRow(element) {
var id = jQuery(element).prop('id');
var url = 'your_back_end.php_file_that_handles_Ajax';//e.g. AjaxHandler.php
var postArg = {};
postArg['BID'] = id;
postArg['ajaxaction'] = 'updateRow';
jQuery.ajax({
url: url,
type: "post",
data: postArg,
success: function (response) {
jQuery('#row_' + id).html(response);
},
error: function(response){
console.log(response);
}
});
}
Your backend file would be pretty simple... I create a class called AjaxHandler and pass all ajax calls to the class for whatever processing I need to do...
Your file could be something like this example...
AjaxHandler.php
<?
$ajaxAction = $_REQUEST['ajaxaction'];
if (!method_exists('ajaxHandler', $ajaxAction)) {
die("No such action {$ajaxAction}");
}
$handler = new ajaxHandler();
$handler->$ajaxAction();
class ajaxHandler
{
function __construct()
{
//just an empty constructor
}
function updateRow()
{
$BID = $_REQUEST['BID'];
$stid = oci_parse($conn, 'SELECT * FROM mytable WHERE BID = {$BID}');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
echo " <td><a id='{$row['BID']}' data-toggle='modal' data-target='#myModal' href='#' onclick='updateRow(this)'>Update</a></td>";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
}
}
This is a very basic async dynamic update using php and ajax...
Hope this helps...

Related

How to make buttons on client side that redirect to a php page with database information

I am brand new to programming and I had a unique (I think) question.
I made a MySql database for storing employee records. I am able to submit new employee data to the db and am able to retrieve employee data from the db and display it in an HTML table.
I want to create buttons on the table for each ID#. Each button would redirect you to a different php page and display the employee information associated with the ID# whose button was clicked.
Does anyone know how would I go about doing this?
echo '<table border="0" cellspacing="25" cellpadding="2">
<tr>
<td>ID</td>
<td>First</td>
<td>Last</td>
<td>SIN</td>
<td>Password</td>
</tr>';
function loadList() {
include_once 'includes/dbh.inc.php';
try {
$sqlarray = "SELECT * FROM employee;";
$result = mysqli_query($conn, $sqlarray);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$employeeID = $row['id'] . "<br>";
$employeeFN = $row['firstname'] . "<br>";
$employeeLN = $row['lastname'] . "<br>";
$employeeSIN = $row['sin_'] . "<br>";
$employeePASS = $row['pass_'] . "<br>";
echo '<tr>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
</tr>';
}
}
else {
echo "error no data";
}
} catch (\Exception $e) {
echo ("error");
}
}
Mate, welcome in the programming world. You can create a anchor tag which will redirect user to a new php page with employee id in URL. check below code:
echo '<tr>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
<td><a href="details.php?id='$employeeID.'>View Details</a></td>
</tr>'
Here you need to create a new php page with details.php name. There you need to get employee id by GET global variable and need to fetch details from database to show. Check below code:
<?php
include_once 'includes/dbh.inc.php';
$employeeId = $_GET['id'];
$sqlarray = "SELECT * FROM employee where id = '".$employeeId."';";
$result = mysqli_query($conn, $sqlarray);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$employeeDetails = mysql_fetch_row($result);
Here $employeeDetails has all data which you can use to render in HTML. But please read little bit about SQL injection before using the same code to avoid crashes. Hope it helps you.
You could do like this by adding <a></a> tag
echo '<tr>
<td><a href="show.php?id='$employeeID.'>Show</a></td>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
</tr>';
And in show.php page get this id by $_GET['id']

How to delete dynamically created table rows without refreshing (preferentially with the standard swipe-to-left-animation)

Sorry, but I have to ask one more question. Google couldn´t help me :(
I try to create a user control management in a CMS.
The problem is that I am completely knew to javascript and jQuery and I have to delete a table row on button click without refreshing the page. The idea is to set the row display:hidden, but I don´t know how to get the id of a row.
Here is my code:
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY id asc");
//$ergebnis = mysql_query($abfrage) or die( mysql_error() );
echo "<table>";
echo"<caption>Mitglieder<br></caption>";
echo"<table border=\"1\" style=\"width:300px\">";
echo "<th>ID</th>
<th>Name</th>
<th>Vorname</th>
<th>Rolle</th>
<th>Funktionen</th>";
//loop, um alle Nutzer zu identifizieren
while($row = mysql_fetch_object($abfrage))
{
echo "<tr>";
echo "<td align=center id =",$row->id,">",$row->id,"</td>";
echo "<td align=center>" ,$row->Name,"</td>";
echo "<td align=center>",$row->Vorname,"</td>";
//Vorbelegung
echo "<td align=center><select><option selected = \"selected\">",$row->Rolle,"</option>";
//loop, um alle Rollen zu identifizieren. AKTUELL: doppelte Rollen werden noch doppelt angezeigt. Eventuell Rollen auslaagern
$file = mysql_query("SELECT Rolle FROM user WHERE 1");
while ($role = mysql_fetch_row($file))
{
if ($role[0]!= $row->Rolle) {
echo "<option value=".$role[0].">",$role[0],"</option>";
}
}
echo "</select></td>";
echo "<td align=center><button type = \"button\" onCLick = \"deleteUser()\">Löschen</button></td>";
}
echo "</table>";
?>
<html>
<script type="text/javascript">
function deleteUser() {
alert("And it works");
document.getElementById(id).style.display = 'none'
}
</script>
</html>
The problem is here:
echo "<td align=center id =",$row->id,">",$row->id,"</td>";
Is this the right way to create an id to every row?
And if somebody knows how to realize it, I want to have an "deleting" (Deleting is obviously the wrong word because it is only hidden) animation.
Thank you in advance!
Ps: I know, that I have to change mysl to SQLi :)
I'm not really a FAN of JQuery because makes you forgeth the very basics of Javascript! it really simplyfies some things but... hmm dunno!
maybe this "function" could help you:
function dropRow(rowId) {
try {
var tblResponse= document.getElementById('tblResponse');
var rowCount = tblResponse.rows.length;
for(ix=0; ix < rowCount;ix++) {
var row = tblResponse.rows[ix];
var id = row.cells[0].childNodes[0].id; //The ID of something what identifies the Row
if(id == 'dropRow'+rowId) {
tblResponse.deleteRow(ix);
rowCount--;
ix--;
}
}
}catch(e) {
alert(e);
}
}
You can use the remove function within jQuery.
You will want to give the ID to the <tr> and not a <td> within the row, next your deleteUser function should take the "id" as an argument, and finally you should delete the row from within the deleteUser function. But you will need a way to inform your database that the user has been deleted, perhaps ajax to an API might work but I don't know how you have your system set up.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function deleteUser(id){
$(id).remove();
// Do something to let the server know the user was deleted
}
</script>
</head>
<body>
<?php
$abfrage= mysql_query("SELECT * FROM user ORDER BY id asc");
echo "<table>";
echo "<caption>Mitglieder<br></caption>";
echo "<table border=\"1\" style=\"width:300px\">";
echo "<thead><tr><td>ID</td><td>Name</td><td>Vorname</td><td>Rolle</td><td>Funktionen</td></td><thead>";
while($row = mysql_fetch_object($abfrage)){
echo "<tr id='".$row->id."'>";
echo "<td align='center'>".$row->id."</td>";
echo "<td align='center'>".$row->Name."</td>";
echo "<td align='center'>".$row->Vorname."</td>";
echo "<td align='center'><select><option selected=\"selected\">".$row->Rolle."</option>";
$file = mysql_query("SELECT Rolle FROM user WHERE 1");
while ($role = mysql_fetch_row($file)){
if ($role[0]!= $row->Rolle)
echo "<option value=".$role[0].">".$role[0]."</option>";
}
echo "</select></td>";
echo "<td align='center'><button type = \"button\" onclick = \"deleteUser(".$row->id.")\">Löschen</button></td>";
echo "</tr>"
}
echo "</table>";
?>
</body>
</html>

Remove a table row in MYSQL using PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've looked through the existing questions and i don't believe they are answering my question.
I have created a table that gets populated using PHP and MySQL. I have got my add function working so the user can ADD a new row, however I would like the user to remove specific rows. Each row has a remove icon that I would like when clicked to remove ONLY that row.
Home.php (where table is created)
<table class="table table-bordered table-striped table-responsive">
<tr class="header">
<td>id</td>
<td>Rep</td>
<td>Date</td>
<td>Name</td>
<td>P_O</td>
<td>Due Date</td>
<td>Terms</td>
<td>Aging</td>
<td>Open Balance</td>
<td>remove</td>
</tr>
<?php
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button></td>";
}
?>
</table>
This is the remove button:
<button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button>
I would like it to remove the row that its currently part of when clicked. Any help?
Here is my new code, however it still doesn't seem to be deleting the row
home.php:
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button action='deletepage.php' method='POST' value='" .$row['id']. "' class='btn btn-danger'> Delete</button></td>";
}
deletepage.php:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_GET['id'])){
$userID = (int) $_GET['id'];
if(!empty($_GET['id'])) {
$delete = mysql_query("DELETE FROM Book1 WHERE id='$userID'");
}
if($delete) {
echo "Record deleted successfully";
}
else {
echo "Sorry, record could not be deleted";
}
}
You can do by directing it to the delete page like this:
Delete
Or with javascript AJAX call:
Delete
and use $.post to the deletion page
UPDATE:
the deletion page deletepage.php may contain the following:
<?php
require('dbconn.php');
if(isset($_POST['id'])){
$userID = (int) $_POST['id'];
if(!empty($_POST['id'])){
$delete = mysql_query("DELETE FROM users WHERE id='$userID'");
}
if($delete){
echo "Record deleted successfully";
}else{
echo "Sorry, record could not be deleted";
}
}
?>
users.php
<?php
require('dbconn.php');
$get = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($get)) {
echo '<p>';
echo $row['id'] . ' - ' . $row['user'];
?>
Delete
</p>
<?php } ?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function confirmDeletion(id){
$.post('deletepage.php', { id:id }, function(data){
alert(data);
location.reload();
});
}
</script>
P.S:
It's very recommended to quit using mysql_query() in this way and instead use PDO to avoid SQL injection
I would change the button to include the value of the row id, by adding a value attribute to the button html:
value='" .$row['id']. "'
You can then capture the click event using jquery / javascript, and use an ajax call to remove the record from your database. It would look something like:
$('.btn-lnk').on('click',function() {
var id = $(this).val();
$.ajax({
type: "POST",
url: "yourPageThatDeletesRow.php",
data: { id: id },
success: function(response) {
if(response === 'success') {
//delete row showing on the page
$(this).closest('tr').remove();
} else {
//handle error
}
} //consider handling ajax error case
});
});
The ajax call will execute the code on yourPageThatDeletesRow.php. You can get the row id using $_POST['id'] and delete the data using that id. If the delete is successful, echo the string 'success'. Consider returning the error from the database if it's not successful, and handling that case in the return of the ajax
Here is a simplified JS Fiddle showing how the passing of the id and row deletion work.
You will need a delete button if your going to do it the way ive done it.
if (isset($_POST['delete'])){
$userid = $_POST['userid'];
$sql = "DELETE FROM users WHERE userid = '$userid';";
if ($conn->query($sql) === true){
//echo 'Click here to view modified patients';
}
}
Use this code:
<?php $temp_pre_ID = $row['id'];?>
<INPUT TYPE="button" onClick="window.location='home.php?Action=del&CusID=<?php echo $temp_pre_ID;?>'" value="Delete">

Calling a PHP function in a dynamically created HTML table

I have a HTML Table that is populated from a mySQL table as seen below:
$sql = "SELECT `ID`,`SaveName`, `CourseNumber`, `FormType`, `POSTString`, `DateModified` FROM `SavedFormsTable` WHERE 1";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Save File Name</th>
<th>Course Number</th>
<th>Date Modified</th>
<th>Load Old Form</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['SaveName'] . "</td>";
echo "<td>" . $row['CourseNumber'] . "</td>";
echo "<td>" . $row['DateModified'] . "</td>";
echo '<td><button type="button" onclick="LoadFormJS('.$row['ID'].');">Load Form!</button>';
echo "</tr>";
}
echo "</table>";
My problem is on the 4th line from the bottom. in the HTML <button>
I am trying to create a button IN THE HTML TABLE that when clicked will call a PHP function. But i have to echo the HTML in order to create the table from the mySQL database.
Is there a clever way of to do this???
The PHP function I need to call:
function LoadFormPHP($ID){
$con=mysqli_connect("","User636626","EasyPassword","pansyc5_SavedForms");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = sprintf("SELECT `POSTString` FROM `SavedFormsTable` WHERE `ID`=%d",$ID);
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
//mysql_close($con);
$_POST = unserialize(base64_decode($row["POSTString"]));
}
The JS function i tried (and failed) to call the PHP function from:
<script>
function LoadFormJS(ID){
alert(ID);
<?php LoadFormPHP(ID) ?>
}
</script>
You cannot mix html (client side) and php (server side) together. For this kind of cases AJAX is a good tool. The onclick can contain a request to a javascript function that fires the request back to your server, and returns the desired HTML.
You just have some syntax issues -
echo '<td><button type="button" onclick="LoadForm(' .$row['ID'] .')">Load Form!</button>';
What you could do to call the PHP function is to surround your button with a form using a hidden input to hold the value of $row['ID']. Clicking on the button would load the proper form at that point and you could ditch the inline JS in favor of a form action.

calling a php function in javascript

I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};

Categories