Get database table row count javascript - javascript

I need to display via a html page the number of rows within my sql database table. with javascript. I cant use php as the frontend of the template is all html.
The admin section of my site uses php and uses the following code to get the number or rows within my channel table.
<?php $qry="select * from channel";
$res=mysqli_query($con,$qry) or die(mysqli_error($con));
$rowcount=mysqli_num_rows($res);
?><?php echo $rowcount; ?>
How can I reproduce the same using html and javascript.
Thanks

What will you count in HTML?
If all rows are displayed as HTML table rows, you could count them. Otherwise you couldn't count rows in a SQL-table to which you don't have access from the frontend.
Counting rows of an HTML table with id="mytable" would look like this:
var num_rows = $('table#mytable tr').size();

Related

Bootstrap Modal - How to provide data from php (database)

This is probably very simple, but am learning PHP, Javascript as I go. I find it easier to learn using real examples than the contrived examples given online.
I am creating an attendance register page, based on selecting a class, then all members of that class ordered by Surname and Firstname.
The table row has it's id set, by PHP, as the record's mem_id, and contains just forename+" "+surname, and some checkboxes.
All this is working fine, but now I have been asked to add a link so that clicking on it brings up a modal containing related data for the person selected. The extra data is already in the $a_fetch array.
Have added a glyphicon link for every row and clicking it displays a modal alright, and by having a javascript function I know I can get the row index and row id
<tbody>
<?php
while($g_fetch = $a_query->fetch_array()) {
$checked = array();
$memid = $g_fetch['mem_id'];
$name = $g_fetch['firstname'].' '.$g_fetch['lastname'];
$attendences = explode(",",$g_fetch['attend']);
for ($x = 0; $x <= 12; $x++) {
if ($attendences[$x]!="0") {
$checked[$x] = 'checked = "checked"';
}
else $checked[$x] = '';
}
echo "<tr id='".$memid."'>";
echo "<td>".$name."</td>";
echo "<td align='center'><div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre'></div>";
for ($y = 0; $y <= 12; $y++) {
echo '<td align="center"><input type="checkbox" value = "" '.$checked[$y].'></td>';
}
}
unset($checked);
unset($attendences);
?>
</tbody>
</table>
I am at a loss as how to proceed - is it even possible to pass data to the modal to display related data?
If it is would I need to run a new query (SELECT), or as the row is the same index as the data in the $A_fetch, and the row id has the correct mem_id is it possible to get the data from the existing $a_fetch array using either of those, or would I need to run a new SELECT?
Many thanks
There are multiple ways to provide data to the modal - and (in my opinion) it depends on how much data you need to pass to your modal and how many rows you have.
I want to describe you two ways:
Light+Easier Solution
If you don't want to display a lot of data and you have just a few rows.
The idea is to add the data directly to each div.glyphicon (as data attributes) and then use it in the modal
In your foreach add it to your model like that:
<div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre' data-link='".$g_fetch['additional_link'] ."' data-moreInfo='".$g_fetch['moreInfo']."'></div>
You haven't posted the modal's HTML or your JS code, but you wrote you are using bootstrap, so stick to
https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content
and fetch/set the relevant data (related clicked glyphicon) as it's described.
More complex solution
For more data / more rows. The additional data is not provided in the inital loaded HTML page - Therefore not all data needs to be loaded in the beginning.
Instead the additional data is loaded via ajax when clicking on one row.
For that you need to provide an additional endpoint (php) which provides the modal content for one row.
Check out second answer in Bootstrap 3 - How to load content in modal body via AJAX?
Basically you have a php file (e.g. getAdditionalData.php)
In this file you access the mem_id via GET
$mem_id = $_GET['mem_id'];
fetch the additional data from database
and print/render out the modal content (full html like in the second answer)
And in JS (inital page) you load the modal content onClick (fetched from php with provided mem_id as parameter)
var clicked = $(e.relatedTarget);
$(this).find(".modal-body").load("%PATH%/getAdditionalData.php?mem_id="+clicked.attr("id"));
I hope it will help you solving your problem and if you need additional infos just let me know. There are more ways to archive your goal but I think this 2 possibilities are enough in the beginning :-)

How to poll database based on table change php + mysql

I want to update my generated table in my php file only when there are changes in the database table but i don't know how to do this. After reading all the many similar questions i still haven't come close to understanding what it is that I am supposed to do.
Im displaying my table within this div <div id="table_holder" class="table-responsive" style="height: 300px;"></div> within my main.php
and this is the JS that I'm using to refresh the table every 5 seconds.
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#table_holder').load('live_table_data.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
This is how im displaying my table in live_data_table.php
$result = $conn->query("select date,student_id, s.s_name as Name, s.s_lname as Last, s.s_email as Email, time from attendance_record A
inner join student s on A.student_id = s.s_id
inner join session b on A.session_id = b.session_id
where b.module_id = 7 and A.date = '2017-03-20' and b.start_time = '16:00'");
?>
<table class="table-responsive" id="live_table">
<thead>
<tr >
<th>Student ID</th>
<th>Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Arrival</th>
<th>Date</th>
</tr>
</thead>
<tbody style="overflow: auto">
<?php
while ($row = $result->fetch_assoc()) {
unset($student_id, $Name, $Last, $Email, $time, $date);
$student_id = $row['student_id'];
$Name = $row['Name'];
$Last = $row['Last'];
$Email = $row['Email'];
$time = $row['time'];
$date = $row['date'];
echo "<tr>";
echo "<td>".$student_id."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Last."</td>";
echo "<td>".$Email."</td>";
echo "<td>".$time."</td>";
echo "<td>".$date."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
My problem is that I've no idea how to dynamically update the table based on if and only if there is a change within the database
Usually people don't do what you are trying to, because making a query which would tell if anything has changed would require the same amount of resources as doing the original query. So the best solution might be to just repeat the query in a fixed interval, like in every minute.
But in case you have a very heavy query, for which you want to reduce the number of times it is done, you can do the following:
Since traditional relational databases have no event-driven aspects, the only way to do this, is to make polls for the changes in fixed intervals. So this as to be solved on the application level, namely: every time you modify the data you update something in the database with the current datetime. There are many possibilities:
You could add a last_modified field to the student table, and each time the code adds or modifies a record it would set there the current time. Then you can either query only the modified records, or check the latest modification time by:
select
max(`last_modified`)
from
`student`
You can create a separate table, which has a record for each tables you want to track. Every time your code adds or modifies a student, then it would set the current time for the student table.
insert into
`track_updates`
(`table_name`, `time`)
values
("student", "2017-03-21 12:59:00")
on duplicate key update
`time` = "2017-03-21 12:59:00"
And then query by the table:
select
`time`
from
`track_updates`
where
`table_name` = "student"
You could even have a table with always a single record in it, containing a single field for the last update time, for all relevant tables.
You can make these kinds of polling more efficient, with techniques like: https://en.wikipedia.org/wiki/Comet_%28programming%29
To know if there has been modification on your table, I can think of :
Check and save the last update time in information_schema
Create a "versionningTable" that is triggered every update of your table(s) data update, insert or delete
Calculate and save a hash of the selected resultset
There might be some other ways to do this.
You can't update content in browser without sending request from frontend. But you can minimize this process. Just create php script, which will output status and result in json.
To make php script understand, when table updated and when not, use hash summ.
When you update any data in database, change this hash.
When you render table, add this hash summ as data-hash="<some hash>" to your table tag.
And when you will send ajax request to php script, add this hash as send data.
Then just compate actual hash and script sended hash. If this not equal, set json status as updated and output actual data.
Then render new data in table with jquery.
However, maybe it is not worth it and you better to leave it as is.
As per the recommendations of many, I decided to go with a different route where by eliminating the refresh of the table every 5 seconds and instead have a button designed to refresh the amount of rows within the table.
<button type="button" onClick="refreshTable()">Refresh</button>
<div id="table_holder" class="table-responsive" style="height: 300px;"></div>
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#table_holder').load('live_table_data.php')};

Yii2: Jquery selecting id of a table cell not working

I am using Yii2 and using this jquery code to access the value of a cell(td) column. I have set the id of the column say 'room_name'
I am using this code which works fine on a form, but in grid-view(table) I am getting a blank alert.
<?php
$script = <<<EOD
alert ($('#room_name').val());
EOD;
$this->registerJs($script);
?>
Do I need to do it differently for tables, as the id is getting repeated over multiple rows.
Thanks for a suggestion.
I got it from #anpsmn. Adding for record for help to others.
$('td.room_name').each(function(){
alert($(this).text());
})

Reorder table rows using php

I am using sort table rows with jQuery using drag and drop method for table sort. Now the issue I am facing is after saving order to DB how can I set the table on refresh page or load?
Means my table is in HTML and I can get order from db in PHP but how can reorder with that sort?
My table structure is like :
`order`->fields ('id'=> int,'order'=>int,'code'=>int)
While in above MySQL table order is used for table row reordering and code for unique table. I am confused and don’t know how to sort out this issue.
Edit3: I deleted a bunch of the stuff i just had, so if you want to see it agian just let me know and i'll send it to you, but this should answer your question:
i see that you said your HTML is already set. Thats an easy fix. Load your html via php like so:
<?
$STH = $DBH->query('SELECT * FROM <table> ORDER BY order');
$STH->setFetchMode(PDO::FETCH_ASSOC);
echo '<div id = "tablediv"><table>
<tr>
<th>My Table Header</th>
</tr>';
while($row = $STH->fetch())
{
echo '<tr>';
echo '<td>My DB Data Via String Concat</td>';
echo '</tr>';
}
echo'</table>';
echo'</div>';
?>
Basically just loop through your mysql result and create table rows based on how many there are with a simple php while loop.
edit 4: added PDO security as suggested by tadman

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

Categories

Resources