Display mysql database report in several pages - php

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"> &#171 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;
}
}

Related

run a constant query against mysql using php without refreshing HTML page

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>

How do I display different table from database on one page using scroll function

Right now, I am working on a project where I need to display data from different tables on one page, one after another using scroll function
For this task I am using ajax, php, mysql.
So here is what I have managed so far:
PHP code:
<?php
$conn = mysqli_connect("127.0.0.1", "Got", "nokia", "myddb");
$feedb = mysqli_query($conn,"SELECT * FROM feedb");
$feedb_count=mysqli_num_rows($feedb);
$photo = mysqli_query($conn,"SELECT * FROM photob");
$photo_count=mysqli_num_rows($photo);
$limito=$_POST["limit"];
$pagefeed=$_POST["start"];
$pagephoto=$_POST["startphoto"];
$pagetexto=$_POST["start3"];
$tumb=$_POST["change"];
if($tumb==0)
{
$query = "SELECT * FROM feedb ORDER BY cid DESC LIMIT $pagefeed , $limito ";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo "
<div class=\"block\">
<img class=\"imago\"src=\"img/$row[cphoto].jpg\">
<span class=\"namo\">$row[cname]</span><br>
<span class=\"texto\">$row[ctext]</span>
</div>"."Page".$pagefeed."Func".$tumb;
}
}
if($tumb==1)
//echo "<br>"."Page".$pagefeed."Func".$tumb;
{
$query = "SELECT * FROM textb ORDER BY cid DESC LIMIT $pagephoto , $limito ";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo "
<div class=\"block\">
<span class=\"namo\">$row[cname]</span><br>
<span class=\"texto\">$row[ctext]</span>
</div>";
}
}
Javascript code:
<script>
$(document).ready(function(){
var limit = 7;
var start = 35;
var start2 = 0;
var start3 = 0;
var action = 'inactive';
var change = 0;
var ncount =0;
if(active='inactive'){
action='active';
load_country_data();
}
function load_country_data()
{
$.ajax({
url:"resout.php",
method:"POST",
data:{limit:limit,start:start,change:change,startphoto:start2},
cache:false,
success:function(dataz)
{
$('#load_data').append(dataz);
if(dataz == '')
{
action = 'inactive';
change++;
if(change==2){action = 'active'; $('#load_data_message').html('Больше нету данных'); }
}
else
{
$('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
action = "inactive";
}
}
});
}
$(window).scroll(function(){
if(($(window).scrollTop() + $(window).height())==$(document).height() && action == 'inactive' && change==0)
{
action = 'active';
start=start+limit; setTimeout(function(){load_country_data();}, 300);
}
else if(($(window).scrollTop() + $(window).height())==$(document).height() && action == 'inactive' && change==1)
{
action = 'active';
setTimeout(function(){load_country_data();}, 300);
start2=((ncount-1)*limit);ncount++;
}
});
});
</script>
but after displaying one base, when it start to dislay second it has an error
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
right after error it displays the second base properly.
I think this problem is because of a method that I chose for displaying second base "star2= (ncount-1)*limit ;ncount++", but I didn't see a different solution.
How can I fix this problem or how can I display different
table in different way?

display row content to a form

i have a table that displays data searched.
what i want to happen is when after i click the row, that data from that row clicked will be displayed in a form.
displaying the table:
search.php
echo '<table id="patientTable" class="w3-table-all w3-hoverable">'
echo '<tr class="w3-yellow"><th>Admission No</th><th>Hospital No</th><th>Patient Name</th></tr>';
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) ) {
echo '<tr onclick=patientClick(this)>';
foreach($row as $key=>$value) {
echo '<td>',$value,'</td>';
//echo $i;
}
echo '</tr>';
}
echo '</table><br />';
the script to attempt to connect to form
function patientClick(x){
var rowInd = x.rowIndex;
var adNo = document.getElementById("patientTable").rows[rowInd].cells[0].innerHTML
var hosNo = document.getElementById("patientTable").rows[rowInd].cells[1].innerHTML;
var patname = document.getElementById("patientTable").rows[rowInd].cells[2].innerHTML;
alert(adNo +"-"+ hosNo +"-"+ patname);//check to display row content
var jsObj = {patname:patname, adNo:adNo, hosNo:hosNo}
$.post('addPN.php', {data:jsObj}, function(data){
$('#displayPatient').html(data);
});
}
the form to display so to save more data
addPN.php
<?php
$arr = json_decode(json_encode($_POST["data"]),true);
$adNo = $arr[0]['adNo'];
$hosNo = $arr[1]['hosNo'];
$patname = $arr[2]['patname'];
echo $adNo;//check to display
echo $hosNo;//check to display
echo $patname;//check to display
?>
<html>
<body>
<form action = "savePN.php" id = "savePNotes" method = "POST">
<input type = "submit" id = "updateButton" value = "Save">
<input type = "text" readonly = "true" id = "adNo" name = "adNo" value = "<?php echo $adNo;?>">
<input type = "text" readonly = "true" id = "hosNo" name = "hosNo" value = "<?php echo $hosNo;?>">
<input type = "text" readonly = "true" id = "patname" name = "patname" value = "<?php echo $patname;?>">
<input type = "text" id = "cn" name = "cn" placeholder = "Contact Number">
<input type = "text" id = "cadd" name = "cadd" placeholder = "Address">
<input type = "text" id = "ctype" name = "ctype" placeholder = "Type">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
this is a bad practice using php as a client, but ajax is one way communication that you cant redirect instantly in serverside
function patientClick(x){
var rowInd = x.rowIndex;
var adNo = document.getElementById("patientTable").rows[rowInd].cells[0].innerHTML
var hosNo = document.getElementById("patientTable").rows[rowInd].cells[1].innerHTML;
var patname = document.getElementById("patientTable").rows[rowInd].cells[2].innerHTML;
alert(adNo +"-"+ hosNo +"-"+ patname);//check to display row content
//here you must construct some JSON object for your data
var jsObj = { pathname: pathname,
adNo: adNo,
hosNo: hosNo }
$.post('searchPatient.php', JSON.stringify({ data : jsObj}) , function(data){
$("#displayPatient").html(data);
});
}
in your server side you should decode your json
use this
$data = json_decode($_POST["data"])
echo $data["adNo"];
and i think you structure is no good and i think its not possible to do what you wanted to do because the form are from php and different file maybe its possible if you use just normal html form so can easily manipulate the form using DOM

How to limit checkbox selection in PHP?

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>

Is it possible to return a table with some constraint in another .php page in ajax and show it in div

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.

Categories