Populate HTML table through PHP - javascript

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.

Related

How to pass an javascript array to an php script

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

onclick() does not work in a table

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.

Passing html table data to function

I've used this site a ton but this is the first time posting. Please be kind. I'm trying to pass data from an HTML table to a function using onclick. I'm able to pass the entire table using onclick="markPaid(transaction.innterText), but I want to be able to pass the data from the current data row only. My best attempt is onclick="markPaid(thistransaction.innterText)"but results in an undefined variable when passed to the function "markPaid". Hopefully this is a clear explanation of the issue.
<table id ="transaction" border="1">
<style>th, td {padding: 10px;}</style>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($transactions))); ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($transactions as $transaction): array_map('htmlentities', $transaction); ?>
<tr>
<td id = "thistransaction"><?php echo implode('</td><td>', $transaction); ?></td>
<td><a class ="btn btn-default" href="invoice.php?ID=<?php echo $transaction['transid']; ?>" target = "_blank">Print Invoice</a> </td>
<?php if($transaction['paid'] == false): ?>
<td><button class = "btn btn-default" onclick="markPaid(thistransaction.innterText)">Mark as Paid</button></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I think you are getting undefined with onclick="markPaid(thistransaction.innterText)" because thistransaction is not unique. You are setting thistransaction as an id on every row of your table in your foreach loop. Try using something unique for each row, maybe the transid you echo to the invoice, $transaction[transid]

2nd data table don't show "no data available" message

I have 2 data tables:
Table 1
<table id="properties_list" class="table">
<thead>
<tr class="backend_tab_header">
<th>Status</th>
<th>Photo</th>
<th>Property ID</th>
<th>Address</th>
<th>Date Created</th>
<th>Owner</th>
</tr>
</thead>
<tbody>
<?php
foreach ($properties as $property)
{
?>
<tr>
<td><?php print $property["status"]; ?></td>
<td class="pic_prop_table"><img class="img-responsive" src="<?php print $property["url"]; ?>" ></td>
<td><?php print $property["prop_id"]; ?></td>
<td><?php print $property["address"]; ?></td>
<td><?php print $property["date_created"]; ?></td>
<td><?php print $property["first_name"]; ?> <?php print $property["last_name"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
Table 2
<table id="messages_list" class="table">
<thead>
<tr class="backend_tab_header">
<th>Property ID</th>
<th>Subject</th>
<th>Message</th>
<th>Received</th>
</tr>
</thead>
<tbody>
<?php
foreach ($properties as $property)
{
?>
<tr>
<td><?php print $messages["from_user"]; ?></td>
<td><?php print $messages["subject"]; ?></td>
<td><?php print $messages["message"]; ?></td>
<td><?php print $messages["date_sent"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
and to fill the arrays call my php functions on top of the page:
$properties = $auth_user->getPropertiesByUser($_SESSION['user_session']);
$messages = $auth_user->getMessages($_SESSION['user_session']);
The data tables are create with JS
jQuery(document).ready(function() {
jQuery('table#properties_list').DataTable( {
//ajax: '../ajax/data/arrays.txt',
scrollY: 200,
scrollCollapse: true,
paging: false
} );
jQuery('table#messages_list').DataTable( {
//ajax: '../ajax/data/arrays.txt',
scrollY: 200,
scrollCollapse: true,
paging: false
} );
});
My problem is that when the first array($properties) return empty the first table show the message "No data available in table" and also when both arrays($properties and $messages) return empty both tables show the message "No data available in table", but when $properties array return with info and $messages array return empty the 2nd table(messages)don't show the "No data available in table" and also creates as much <td> elements as <td> elements in the firs table(properties). Can anyone tell me what could be the cause of this behaviour?
Thanks in advance
probably it's because both of the for each in pop use the $properties. On second loop, it gets the $prperties of the first.
Try to set $properties = array() before getting the values or use another variable name.

Javascript comparison for a table row to highlight a row in red (CakePHP)

How do I find the right approach to getting this comparison to work? I've tried all kinds of approaches. I even used ids, but they don't respond. If I do this "gumboots" string check though, it does work. "gumboots" was just a value for a product name that existed somewhere on the table. This is how I know I do not need PHP at all for this, despite the tables displayed in PHP in the Index view below. Any idea? I would appreciate it.
Here's the javascript
$('#example tbody tr td').each(function()
{
//var p_no_in_stock = parseInt($('#p_no_in_stock')).val();
//var p_reorder_quantity = parseInt($('#p_reorder_quantity')).val();
var p_no_in_stock = parseInt(document.getElementById('p_no_in_stock')).value;
var p_reorder_quantity = parseInt(document.getElementById('p_reorder_quantity')).value;
//if ($product['Product']['p_no_in_stock'].val() < $product['Product']['p_reorder_quantity'].val())
if ($(this).text() == "gumboots")
//if ($(this).p_no_in_stock < $(this).p_reorder_quantity)
{
//$("#row_" +" td").effect("highlight", {}, 1500);
$(this).closest('tr').attr('style','background-color:red');
$(this).parent().css('background-color','red');
$(this).parent().attr('style','background-color:red');
$(this).parent().addClass('highlight');
$(this).parent().css('font-weight','bold');
}
});
And this is the application in a View called Products.index
<div class="active">
<h2><?php echo __('Products'); ?></h2>
<table cellpadding="0" cellspacing="0" class="table table-striped table-bordered" id ="example">
<tr>
<th><?php echo $this->Paginator->sort('p_name', 'Name'); ?></th>
<th><?php echo $this->Paginator->sort('category_name', 'Category'); ?></th>
<th><?php echo $this->Paginator->sort('p_no_in_stock','No. in Stock'); ?></th>
<th><?php echo $this->Paginator->sort('p_reorder_quantity', 'Re-order Quantity'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo h($product['Product']['p_name']); ?></td>
<td> <?php echo $this->Html->link($product['Category']['category_name'],
array('controller' => 'categories', 'action' => 'view', $product['Category']['id'])); ?>
</td>
<td id = "p_no_in_stock" type ="number" ><?php echo h($product['Product']['p_no_in_stock']); ?> </td>
<td id ="p_reorder_quantity" type ="number" ><?php echo h($product['Product']['p_reorder_quantity']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $product['Product']['id']), array('class' => 'btn btn-mini')); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $product['Product']['id']), array('class' => 'btn btn-mini')); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $product['Product']['id']), array('class' => 'btn btn-mini'), __('Are you sure you want to delete # %s?', $product['Product']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Thanks in advance.
Is this what you're asking?
http://jsfiddle.net/SinisterSystems/z9SE7/1/
HTML:
<table>
<tr>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
</tr>
<tr>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
<td>Test</td>
</tr>
</table>
CSS:
tr:hover td {
background:#F00;
}
I am sending you mine code, please modify it accordingly....
The PHP Code is as -
<?php
if($num>0)
{
echo '<table width="100%" id="dep_table" style="margin-top:10px;" cellspacing="1" cellpadding="2" border="0">';
echo '<tr bgcolor="#4682B4">';
echo '<th>Editor</th>';
echo '<th>Department Id</th>';
echo '<th>Department Name</th>';
echo '</tr>';
$i=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$i++;
if($i % 2 == 0)
{
$bgcolor= "#6AA2C3";
}
else
{
$bgcolor= "#A2B5CD";
}
//extract row, this will make $row['firstname'] to just $firstname only
extract($row);
//creating new table row per record
echo "<tr bgcolor='$bgcolor' id='$DeptId' name='edit_tr'>";
echo '<td id="edit"><input id="edit" type="radio" name="deptid" value="DeptId" ?></td>';
echo "<td class='format'>{$row['DeptId']}</td>";
echo "<td class='format'>{$row['DeptName']}</td>";
echo "</tr>";
}
echo "</table>";
}
echo "</div>";
The JS for corresponding code is as -
$(document).ready(function() {
row_color();
$('#dep_table tr').click(function(e) {
$(this).find('td input:radio').prop('checked', true);
/* submit_fxn();
$('#form_ndesg').submit(function(e) {
return false;
});*/
});
});
//******* 1 Div Fade In/Out effect *******
function row_color(){
$('#dep_table tr').not(':first').hover(function(){
$(this).addClass('hover');
},function(){
$(this).removeClass('hover');
});
};
The corresponding CSS code is as -
tr.hover{
background-color:#E7ECB8;
color:#990000;
}
You will move your mouse on the table, it will change the row color as well as rwo text color and when you click on particular row, it will enable the row by selecting radio button..
If this answer is helpful for you then please like it for answer, so that others can use it for reference.... Thanks and best of luck

Categories