I have a normal html table filled with database entries.
I got a plugin to select multiple rows in this table.
Now i want to click on a button and delete the database entry so I need to get the id out of the array and but it in my php script.
But I have not really an idea how to do it.
</div>
<table id="myTable" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM artikel;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td> <?php echo $row["id"]?></td> <?php
?> <td> <?php echo $row["artikelnummer"]?></td> <?php
?> <td> <?php echo $row["name"]?></td> <?php
?> <td> <?php echo $row["preis"]?> €</td> </tr><?php
}
}
?>
</tbody>
</table>
</div>
var $rows = [];
$(function() {
console.log( "ready!" );
// start plugin
$('#myTable').TableSelection({
sort : true, // sort or not (true | false)
status : 'multiple', // single or multiple selection (default is 'single')
}, function(obj){ // callback function return selected rows array
$rows = obj.rows;
});
});
<?php
include_once 'dbh.inc.php';
$artid = ???;
$sql = "DELETE FROM artikel WHERE id= $artid;";
mysqli_query($conn, $sql);
header("Location: ../index.php?daten=success");
You can do it with html attributes. I make a example for you with html, css and javascript.
this is your html.
<table id="tableSelected" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>1-1</td>
<td>Test</td>
<td>1</td>
</tr>
<tr data-id="2">
<td>2</td>
<td>2-1</td>
<td>Foo</td>
<td>1</td>
</tr>
</tbody>
</table>
as you can see, every "tr" tag has "data-id" attribute.
var $rows = [];
$(function() {
$('#tableSelected').TableSelection({
sort : true,
status : 'multiple',
}, function(obj) {
$.each(obj.rows, function(i, row){
var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
});
});
});
Note: https://codepen.io/yusufilkeroguz/pen/vqPgzZ you can see live preview from here :)
Related
I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
$.ajax({
type: "post",
url: "products.php",
data: {id:id},
success: function(){
$(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
}
});
}
}
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>
I have a data table in which there are columns and rows and one of them is a copy button which onclick() initiates a copy function and copies a particular row to the clipboard, it works normally on the first page but when I use the search or the pagination it does not work and the button does not initiate the javascript function.
I searched and found in StackOverflow that I need to reinitiate the data table, which I tried but it gives an error
DataTables warning: table id=datatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
i have used the modified code that I tried after I searched StackOverflow after which it gives an error
DataTables warning: table id=datatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
('#datatable').dataTable({ "fnDrawCallback": function(oSettings) {
//code
}});
});
<table id="datatable" class="table table-striped table-bordered" class="dass">
<thead>
<tr>
<th>No.</th>
<th>Student ID</th>
<th>Reference</th>
<th>First Name</th>
<th>Last Name</th>
<th>Copy</th>
</tr>
</thead>
<tbody>
<?php
$numm=1;
$stmt = $DB_con->prepare("SELECT * FROM asd);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{ ?>
<tr>
<td>
<?php echo $row['id']; ?>
</td>
<td>
<?php echo strtoupper($row['stid']); ?>
</td>
<td>
<?php echo $row['ref']; ?>
</td>
<td>
<?php echo $row['fname']; ?>
</td>
<td>
<?php echo $row['lname']; ?>
</td>
<td>
<button onclick="textToClipboard<?php echo $numm;?>()">Copy</button>
</td>
<th>
<script>
function textToClipboard <?php echo $numm;?> () {
var space = " ";
var x = document.getElementById('datatable').rows[<?php echo $numm;>].cells[1].innerHTML;
var y = document.getElementById('datatable').rows[<?php echo $numm;?>].cells[2].innerHTML;
var z = document.getElementById('datatable').rows[<?php echo $numm;?>].cells[3].innerHTML;
var text = x.concat(space, y, space, z, space, q, space, w);
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
</script>
</th>
</tr>
<?php $numm++;
} ?>
</tbody>
How can I bind it with the data table?
It's not really a good practice to redefine a function again and again in a loop like this - that is what's parameters are for. I can't test this code, but here's an approach i would recommend:
<script>
function textToClipboard(numm) {
var space = " ";
var x = document.getElementById('datatable').rows[numm].cells[1].innerHTML;
var y = document.getElementById('datatable').rows[numm].cells[2].innerHTML;
var z = document.getElementById('datatable').rows[numm].cells[3].innerHTML;
var text = x.concat(space,y,space, z,space, q,space, w);
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
</script>
<table id="datatable" class="table table-striped table-bordered"
class="dass">
<thead>
<tr>
<th>No.</th>
<th>Student ID</th>
<th>Reference</th>
<th>First Name</th>
<th>Last Name</th>
<th>Copy</th>
</tr>
</thead>
<tbody>
<?php
$numm=1;
$stmt = $DB_con->prepare("SELECT * FROM asd");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr><td><?php echo $row['id']; ?></td>
<td><?php echo strtoupper($row['stid']); ?>
</td>
<td><?php echo $row['ref']; ?></td>
<td><?php echo $row['fname']; ?></td>
<td><?php echo $row['lname']; ?></td>
<td><button onclick="textToClipboard(<?php echo $numm;?>)">>Copy</button></td>
</tr>
<?php
$numm++;
} ?></tbody>
So define one parametered function first, and then call that later.
Furthermore, I'm unsure on how datatables handles selecting .rows[numm] after you search or use the pagination function. Therefore an even safer solution would involve passing all your required parameters in the function call, something like this:
onClick="textToClipboard($row['ref'], $row['fname'], $row['lname'])"
But this relies entirely on what you're trying to achieve here.
To avoid Cannot reinitialise DataTable Warning, just add
"destroy": true,
while initialising it. That will reinitialise a datatable again when you call it second time.
Read more:
https://datatables.net/reference/option/destroy
https://datatables.net/reference/api/destroy() -- destroy method
i created an appointments table and added two links to accept and reject appointments. the links are displayed in every row of the table but when i click it the text accept & reject are only displayed in the first row & I also need to know how to insert the text that appears after the button click into the db i would request someone to pls provide me some help thanks!
<form method="post" action="delete.php" >
<table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">
<thead>
<tr>
<th>appoinment ID</th>
<th>Date</th>
<th>time</th>
<th>teacher</th>
<th>parent</th>
<th> accept/reject </th>
<th>label</th>
</tr>
</thead>
<tbody>
<?php
$query=mysqli_query($conn, "select * from `app` left join `par` on par.par_id=app.par_id
left join `tea` on tea.tea_id=app.tea_id
ORDER BY app_id DESC");
if($query === false)
{
throw new Exception(mysql_error($conn));
}
while($row=mysqli_fetch_array($query))
{
$ann_id=$row['app_id'];
$date=$row['date'];
$msg=$row['time'];
$username = $row['username'];
$username = $row['p_username'];
?>
<tr>
<td><?php echo $row['app_id'] ?></td>
<td> <?php echo date('j/m/y',strtotime($row['date'])); ?></td>
<td><?php echo $row['time'] ?></td>
<td><?php echo $row['p_username'] ?></td>
<td><?php echo $row['username'] ?></td>
<td> reject
accept
</td>
<td>
<div id="chgtext">PENDING</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
In jQuery it would look like this:
<td>
reject
accept
</td>
<td>
<div class="chgtext">PENDING</div>
</td>
Then, before closing body tag:
<script>
$(document).ready(function(){
$('.reject').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('reject');
});
$('.accept').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('accept');
});
});
</script>
You can make the code shorter, but I wanted to show you how it works step by step.
I tried to update 1 row in table with ajax triggered by onchange dropdown, I succeed update data but it updating all data in my table.
so how I can get unique value (eg :User ID) to pass it from ajax to my php so i can update it only 1 row?
here's my code :
my table (transactions.php)
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();">
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and here my ajax
function updatetransactions(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:"status="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
my updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$penjualan_id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
I assume that you update all of your rows in your database, with no WHERE condition. In your script, lets also get the corresponding id of that row in your database.
Lets assign first the id for each table row:
while($data1 = mysqli_fetch_array($query)){
?>
<tr id="<?=($data1['user_id'])?>">
Then, lets change how you trigger your javascript. Lets first change the <select> field:
<select name="pilihstatus" id="pilihstatus" class="pilihstatus">
Then, get the corresponding id using the script below:
$(".pilihstatus").change(function(){
var elem = $(this),
selecteditem = elem.val(),
id = elem.closest('tr').attr('id');
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data: {'status':selecteditem, 'id':id},
success:function(data){
alert('Successfully updated mysql database');
}
});
});
And on your updatestatustransaksi.php file (please use prepared statement):
$stmt = $koneksi->prepare("UPDATE `konf_transf` SET `status` = ? WHERE `id` = ?");
$stmt->bind_param("si", $_POST['selecteditem'], $_POST['id']);
$stmt->execute();
$stmt->close();
Try adding data_id attribute to select
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>User ID</th>
<th>Pengirim</th>
<th>Jumlah Transfer</th>
<th>Berita Acara</th>
<th>Status</th>
<th>Rincian</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($koneksi, "select * from konf_transf order by tanggal desc limit 7 ");
while($data1 = mysqli_fetch_array($query)){
?>
<tr>
<td>
<center><?php echo $data1['usr_id']; ?></center>
</td>
<td>
<center><?php echo $data1['nm_pengirim']; ?></center>
</td>
<td>
<center>Rp. <?php echo number_format($data1['jmlh_transf'],0,'','.'); ?>,-</center>
</td>
<td>
<center><?php echo $data1['berita_acara']; ?></center>
</td>
<td>
<center><?php echo $data1['status']; ?></center>
</td>
<td>
<center>
<select name="pilihstatus" id="pilihstatus" onchange="updatetransactions();" data_id='<?php echo $data1['usr_id']; ?>'>
<option value="Pilihan">Pilihan</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</center>
</td>
</tr>
<?php } ?>
</tbody>
</table>
and get that data_id value in your function
function updatetransactions(){
var status = $('select option:selected').text();
var status = $('select').attr('data_id');
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"updatestatustransaksi.php",
data:{'status'=status,'id'=id}
success:function(data){
alert('Successfully updated mysql database');
}
});
}
and at your updatestatustransaksi.php
<?php
require_once("koneksi.php");
session_start();
if (!isset($_SESSION['username'])) {
echo "<script>alert('You must register an account first, we will redirect you to register page !'); window.location = 'registuser.php'</script>";
}
$dataupd = $_POST["status"];
$id = $_POST["id"];
$query = mysqli_query($koneksi, "UPDATE `konf_transf` SET `status` = '$dataupd' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Update Success.'); window.location = 'transactions.php' </script>";
} else {
echo "<script>alert('Update Failure.'); window.location = 'transactions.php' </script>";
}
Have you initialised $penjualan_id? I think you need to initialise it like this:
$penjualan_id=$_SESSION['user_id']
I am looking for a way, to populate an HTML table through PHP when the HTML document is loaded.
I have a php file which creates the required table data:
echo <table id="mytable" ... </table>
The output of this PHP script should be written into the html file during its loading time.
Is there any way to accomplish this? Maybe through JavaScript?
If you have data that is stored in row-major order (that is, your data is an array of rows, rather than columns, of data), you must keep track of the columns to print. This is a typical way to receive data from a MySQL database.
You can do this by looking at your first row, using $columns = array_keys($row), or simply hard-code the column keys if they are known in advance like I have done in the following example.
<?php
$data = [
[
"name" => "Alice",
"email" => "alice#example.com",
"home_address" => "Alice Lane 61"
],
[
"name" => "Bob",
"age" => 16,
"home_address" => "Bob St. 42"
]
];
$columns = [ "name", "age", "email", "home_address" ];
?>
<html>
<body>
<table>
<tr>
<?php foreach($columns as $column) { ?>
<th><?php echo $column; ?></th>
<?php } ?>
</tr>
<?php foreach ($data as $row) { ?>
<tr>
<?php foreach($columns as $column) { ?>
<td>
<?php
if (isset($row[$column])) {
echo $row[$column];
} else {
echo "N/A";
}
?>
</td>
<?php } // end $column foreach ?>
</tr>
<?php } // end $row foreach ?>
</table>
</body>
</html>
Note that not all rows have the same columns here. This is handled in the if-statement in the table.
This example outputs:
<html>
<body>
<table>
<tr>
<th>name</th>
<th>age</th>
<th>email</th>
<th>home_address</th>
</tr>
<tr>
<td>Alice </td>
<td>N/A </td>
<td>alice#example.com </td>
<td>Alice Lane 61 </td>
</tr>
<tr>
<td>Bob </td>
<td>16 </td>
<td>N/A </td>
<td>Bob St. 42 </td>
</tr>
</table>
</body>
</html>
This will get you started
<table>
<thead>
<tr>
<th>Row One</th>
<th>Row Two</th>
</tr>
</thead>
<tbody>
<?php foreach( $array as $key ) { ?>
<tr>
<td><?php echo $key[ 'rowOne' ]; ?></td>
<td><?php echo $key[ 'rowTwo' ]; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
You loop through each row in your array and echo out the information you need. You really need to do some PHP tutorials and you will understand how to loop arrays.