Im looking at outputting mysql query results into a table on a php page where the 1st column of the table is the result and the 2nd column is populated with a Javascript timer
however my goal is to have it so that when data comes into the mysql database it display on the table and then when it stops being picked up by the query remove it from the table
the issue i face however is im not sure how to do this without resetting the javascript timer everytime the query is run,
I have gone through a couple of questions that have mentioned to use ajax and this would be fine but im not sure what i would put the HTML side
EDIT:
the below is now my second attempt code using ajax but i cant get the table to display it errors as unexpected token < line 27
my current page load Code to call the data is as followed:
PHP
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = "SELECT
*
FROM
(SELECT
beacon,location,
COUNT(location) AS counter
FROM `track`
WHERE `date` = CURDATE() and `time` > NOW() - interval 60 second
GROUP BY beacon) AS SubQueryTable
ORDER BY beacon + 0 ASC;";
$result = $conn->query($sql);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$conn->close();
?>
HTML
$.get('vendor/fetch.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
(unexpexted token here)
<table id="table">
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr style="background-color: <?php echo $row['item.location'];?>">
<td><?php echo $row['item.beacon'];?></td>
<td> <span class='minutes'>00</span>:<span class='seconds'>00</span>
</td>
</tr>
<?php }
mysqli_close($con);
?>
</table>
});
});
function updateTable() {
//console.log('function called');
$.get('vendor/fetch.php', function(response) {
response.forEach(function(item, index) {
console.log(item.beacon);
});
});
var updateTableInterval = setInterval(updateTable, 100);
};
</script>
</head>
<body>
<script>
var sec = 0;
function pad(val) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval(function () {
$(".seconds").html(pad(++sec % 60));
$(".minutes").html(pad(parseInt(sec / 60, 10)));
}, 1000);
</script>
</body>
Related
I have 2 php files one that retrieve from database, other one take each value came from the database. the problem: data is being sent as whole not row by row. so I can not have each value seperatly. I am trying to find smart way to do so.
first file:
$host = 'localhost';
$user = 'root';
$pass = '';
$db_name="bbbb";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array(); // create an array
while( $row = $result->fetch_assoc()) {
echo $row ['input']; //if my database have 2 rows one with value t1 and other with t2.
}
?>
second file:
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
retrieveData();
});
function retrieveData(){
$.post('quick.php',{}, function(data){
window.alert(data);
});
}
</script>
the output i have is a single alert with (t1 t2)
my desire output to be 2 alerts window. first one with value t1 second with value t2.
try This:
use json to your server side,
while( $row = $result->fetch_assoc()) {
echo json_encode($row['input']);
}
and on your second file:
$.post('quick.php',{}, function(data){
window.alert(data);
},"json");
So far I have been able to get data from MYSQL and display it as a checklist using PHP and HTML. Now I would like to limit the number of checkboxes that can be selected at a time. Javascript doesn't seem to be working with my PHP code.
EDIT: I've included my JScript below which is currently not workng. This JScript only works when I use it with manually created html checklists but not the one I have made below using MYSQL data. How can I fix my Javascript part so this works?
Here is my code:
<?php
$username = "root";
$password = "test";
$hostname = "localhost";
$dbname = "major_degrees";
$str='';
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT degree_name FROM majors";
$result = $conn->query($sql);
$out = '';
$cnt = 0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$cnt++;
$out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';
}
echo $out;
}
$conn->close();
?>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script>
$out.on("click", ":checkbox", function(event){
$(":checkbox:not(:checked)", this.form).prop("disabled", function(){
return $(this.form).find(":checkbox:checked").length == 2;
});
});
</script>
try this:
<script>
$(".someclass").change(function() {
var count = $(".someclass:checked").length; //get count of checked checkboxes
if (count > 3) {
alert("Only 3 options allowed..!");
$(this).prop('checked', false); // turn this one off
}
});
</script>
I want to do is display the result of my count.php in my index page. My plan is to auto count the number of rows of user_code and display the result in the index page everytime the page is visited or viewed.
My problem is that the ajax script doesnt recieve the result of count.php to display it in count inputbox on index page.
index page:
<input type="text" value="1" name="countValue" id="countValue" style="width: 12px;" /><br />
Count: <input type="text" name="count" id="count" readonly="readonly" /><br /><br /><br />
<script>
$(document).ready(function(){
var countTimer = setInterval(
function ()
{
codeValue();
}, 500);
var $count = $('#count');
function codeValue(){
$.ajax({
url:"count.php",
type:"GET",
data: { term : $('#countValue').val() },
dataType:"JSON",
success: function(result) {
$("#count").val(result.user_code);
}
});
};
});
</script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $_GET['term'];
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT user_code FROM students";
$query = $dbc->prepare($sql);
$query->execute();
$num_rows = $query->rowCount();
echo json_encode(array('user_code'=>$num_rows));
}
?>
Your problem
echo $_GET['term'];
This breaks the expected JSON format that your script is meant to produce. Also, you aren't even using any request parameters so I don't know why you'd even bother.
Here's your PHP, all cleaned up
<?php
try {
$dbc = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $dbc->query('SELECT COUNT(1) FROM students');
header('Content-type: application/json');
echo json_encode(['user_code' => $stmt->fetchColumn()];
} catch (Exception $e) {
http_response_code(500);
echo $e->getMessage();
}
I'd also suggest adding an error callback to your $.ajax options to handle HTTP errors.
i try your code and it works for my table i have (4) records! check your query if there is data
make sure you have jquery file in your header. I did not change anything your html file. I just create my own query on my table. then okay.
You need to create a div in indexfile and id of that div is provided in ajax file,so as to populate data form count.php in that div.
Here i will give you a similar type of example, Try it by making your related changes
index.php
<div id="content">
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'count.php',
success: function(data) {
$('#content').html(data);
}
});
<script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$con=mysqli_connect($host,$user,$pass,$db);
$result = mysqli_query($con,"SELECT user_code FROM students");
?>
<table>//this table will be loaded in div
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['user_code']; ?></td>
</tr>
<?php
}
?>
</table>
You can also add autorefresh ajax script which will only reload only particular div after specific time interval(1 sec in below code) without reloading whole page
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#content').load('count.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
when i click the today button, it goes to updatetoday.php page where i select a query and display it in call back of an ajax and display the table in .php file to div with id #test. but it display's error as Uncaught TypeError: Illegal invocation
$(document).ready(function(){
$('#today').click(function()
{
alert("hi");
$.ajax({
url:'updatetoday.php',
data:{update:today}, // pass data
success:function(result)
{$( "#test" ).html(result);}
});
});
});
updatetoday.php
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['update']==today) //taking
{
echo "<table align='center' border='1' cellspacing='2'><tr><th>Book_id</th><th>Name</th><th>Phone Number</th><th>Email Address</th><th>Start Date</th><th>Source</th><th>Destination</th><th>Morning Time</th><th>Evening Time</th><th>Duration</th><th>Days Off</th><th>Date Off</th><th>Current Status</th><th>Call Counter</th><th>Option</th><th>Calender</th><th>Save</th></tr><br><br><br>
<?php
$query_book = 'Select * from `booking` where validity = 1 limit 5';
$result_book = mysql_query($query_book);
while($row = mysql_fetch_assoc($result_book))
{
$user_id = $row['user_id'];
// query for customer table
$query_cus = 'Select * from `customer` where user_id = $user_id limit 5';
$result_cus = mysql_query($query_cus);
$row_cus = mysql_fetch_assoc($result_cus);
$name = $row_cus['user_id'];
$email = $row_cus['email_id'];
$mobile_number = $row_cus['mobile_number'];
$current_status = $row['valid'];
$startdate = $row['start_date_timestamp'];
if($current_status == '1')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>Reg</p>';
}
else if($current_status == '2')
{
$status = '<p style='color:green;font-weight:600;font-size:19px'>New</p>';
}
else if ($current_status == '3.1' )
{
$status = '<p style='color:red;font-weight:600;font-size:19px'>R</p>';
}
?>
<tr align='center'><td class='bookid'><?=$row['book_id']?></td><td ><?=$row_cus['name']?></td><td ><?=$row_cus['mobile_number']?></td><td ><?=$row_cus['email_id']?></td><td><?=$row['start_date_timestamp']?></td><td ><?=$row['source']?></td><td ><?=$row['destination']?></td><td ><?=$row['mor_timestamp']?></td>
<td><?=$row['eve_timestamp']?></td><td><?=$row['duration']?></td><td ><?=$row['days_off']?></td><td ><?=$row['date_off']?></td>
<td><?=$row['current_status']?></td ><td ><?=$row['call_counter']?></td>
<td><select class='sel' name='select_option'><option value='NULL'>Select An Option</option><option value='taking'>Taking</option><option value='later-def'>Later Defined</option><option value='later-undef'>Later Undefined</option><option value='outofrange'>Out Of Range</option><option value='rejected'>Rejected</option><option value='norespond'>No Respond</option></select></td><td><input type='text' class='cal' size='6' disabled='disabled' value='<?=$startdate?>'/></td><td><button id='<?php echo $row['book_id'];?>' class='save'>Save</button></td></tr>
<?php
}//booking table while ends
echo '</table>';
?>
</div>";
}
?>
To fix your problem you must change the line :
data:{update:today}, // pass data
to :
data:{update:'today'}, // pass data
in your code today is a string not a varible
Change the line :
success:function(data)
to :
success:function(result)
You are assigning the result from the php to a variable called data and in
{$( "#test" ).html(result);}
trying to display inside the #test div a variable called result.
I have a mysql database with some data. Now i want to show you mysql data to all. with edit option.
<?php
$username = "VKSolutions";
$password = "VKSolutions#1";
$hostname = "VKSolutions.hostedresource.com";
$database = "VKSolutions";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
$query= 'SELECT * FROM customer_details';
$result = mysql_query($query)
or die ('Error in query');
echo '<table width=80% border=1 align="center">';
echo '<tr><td><b>ID</b></td><td width="20px"><b>Name</b></td><td width="25px"> <b>Telephone</b></td><td width="30px"><b>E-mail</b></td><td width="20px"><b>Country Applying for</b></td><td width="20px"><b>Visa Categeory</b></td><td width="20px"><b>Other Categeory</b></td><td width="20px"><b>Passport No</b></td><td width="50px"> <b>Remarks</b></td></tr>';
while ($row=mysql_fetch_row($result))
{
echo '<tr>';
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '</tr>';
}
echo '</table>';
mysql_free_result($result);
mysql_close($dbhandle);
?>
I need some modifications in this code like
1) MySql data displays in a single page. but not i want. I need to display data with several pages like (page1,page2,page3,.....page54... etc)
2) and also give edit option when a user want to change.
Thanks.
You need to add LIMIT to your select statement.
If you read here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
So you would change your statement to:
SELECT * FROM customer_details LIMIT 0,20
This would get the first 20 records, then to get the next lot of results:
SELECT * FROM customer_details LIMIT 20,20
The numbers after the limit are, the first one is where it still start and the second one is how many to return.
I hope this points you in the right direction.
hey if you want to show data with pages use pagination also if you want to edit the value than you have to show data in a text box like this and send via form
<?php
$username = "VKSolutions";
$password = "VKSolutions#1";
$hostname = "VKSolutions.hostedresource.com";
$database = "VKSolutions";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
$query= 'SELECT * FROM customer_details';
$result = mysql_query($query)
or die ('Error in query');
?>
<table width=80% border=1 align="center" id=pag>
<tr><td><b>ID</b></td><td width="20px"><b>Name</b></td><td width="25px"><b>Telephone</b></td><td width="30px"> <b>E-mail</b></td><td width="20px"><b>Country Applying for</b></td><td width="20px"><b>Visa Categeory</b></td><td width="20px"><b>Other Categeory</b></td><td width="20px"><b>Passport No</b></td><td width="50px"><b>Remarks</b></td></tr>
<?php
while ($row=mysql_fetch_row($result))
{
?>
<tr>
<td><input type="text" name="newid" value="<?php echo $row[0];?>" /></td>
<td><input type="text" name="newname" value="<?php echo $row[1];?>" /></td>
<td><input type="text" name="aaaa" value="<?php echo $row[2];?>" /></td>
......
</tr>
<?php
}
?>
</table>
//pagination code
<div class="pagination" align="center" >
<div id="pageNavPosition"></div>
</div>
<script type="text/javascript"><!--
var pager = new Pager('pag',10); // pag is id of table and 10 is no of records you want to show in a page. you can change if you want
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
//--></script>
</div>
<?php
mysql_free_result($result);
mysql_close($dbhandle);
?>
in the head section add this.
<script type="text/javascript" src="paging.js"></script> /* adding javascript pagination source page */
code for paging.js goes here. just copy and paste the code in a file name paging.js
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage + 1;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> ';
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> Next ยป</span>';
element.innerHTML = pagerHtml;
}
}