I'm having difficulty iterating through records while scrolling window. My initial thought was to load enough records to fit on screen then load an additional set when window scrolled to bottom. I've tried using session / variables to pass some counter to a function, no luck. The code below returns enough records to fit window height but with 0,10 limit. What would be a simple method to resolve this?
Another question is should I use LIMIT or ID > + LIMIT on the Mysql query?
$(function(){
setInterval(function(){
var totalHeight, currentScroll, visibleHeight;
if (document.documentElement.scrollTop)
{ currentScroll = document.documentElement.scrollTop; }
else
{ currentScroll = document.body.scrollTop; }
totalHeight = document.body.offsetHeight;
visibleHeight = document.documentElement.clientHeight;
if (totalHeight <= currentScroll + visibleHeight )
{
$.get('infinite_pull.php', function(data) {
$('body').append(data);
//alert('Load was performed.');
});
}
else
{
$('.dd').css('background-color','white');
}
}
, 100);
});
PHP
<?php
session_start();
mysql_connect('localhost','root','');
mysql_select_db('project5');
$query = "select user_email from users limit 0,10;";
$results= mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['0'] . '<br/>';
}
?>
to call the php file multiple times sound bad,
all that overhead proberly worse then getting all at once.
can't you just calculate how many you need, and ask for that number?
<?php
$from = (int) $_GET['from'];
$count = (int) $_GET['count'];
mysql_connect('localhost','root','');
mysql_select_db('project5');
$query = "select user_email from users limit {$from},{$count};";
$results= mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['0'] . '<br/>';
}
?>
i also think you should add an order by, to be sure the result always gets in the same order.
Use LIMIT, which combines a offset (1st param) and number of rows to get (2nd param). Here's a short example of pagination that get's the 7th page of a 100 numbers 7 at a time.
<?php
$arr = array();
for ( $x = 0; $x < 100; $x += 1 ) {
$arr[] = $x;
};
$page = 7;
$per_page = 7;
$current_page = 1;
for ( $z = 0; $z < count( $arr ); $z += 1 ) {
if ( 0 === ( $z % $per_page ) ) {
$current_page += 1;
}
if ( $current_page === $page ) {
$num_results = $current_page * $per_page;
$query = "select user_email from users limit {$num_results},{$per_page};";
echo "value $z on page $page via $query \n";
}
}
?>
Output:
$ php pagination.php
value 35 on page 7 via select user_email from users limit 49,7;
value 36 on page 7 via select user_email from users limit 49,7;
value 37 on page 7 via select user_email from users limit 49,7;
value 38 on page 7 via select user_email from users limit 49,7;
value 39 on page 7 via select user_email from users limit 49,7;
value 40 on page 7 via select user_email from users limit 49,7;
value 41 on page 7 via select user_email from users limit 49,7;
Related
i am using image gallery here is the link of code image gallery -> https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox
the code is working fine on other page where i have not applied the pagination,
But the Problem is →
I have 4 images in gallery.
when image 1 is active OnClick << 1 PREV it doesn't show image 4
and When image 4 is active OnClick NEXT 4 >> its doesn't show any image
(But On other page where i have not applied pagination result , the image Slide is displaying properly just like this link → https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox )
like link Example → -3 -2 -1 <Prev 1 2 3 4 Next> 1+ 2+ .. ( Working Fine showing the image )
(pagination applied page ( Noimage -1 ) <<Prev 1 2 3 4 Next>> ( Noimage 4+ )
But When I Changed the per page result in pagination from 8 to 1 its work fine its show all image in -PREV and Next+
AND When i change the → $per_page = 8; -- To → $per_page = 1; its Work fine.
i think it is because of the [i] or [ 1 , -1 ] value in of both pagination and image slide
Can anyone pls Advice, how to solve this image No display problem
<?php
include('includes/db_msqli.php');
if (!isset($_SESSION['id'])) {
header("Location: login");
die();
}
?>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$strKeyword = null;
if(isset($_POST["txtKeyword"]))
{
$strKeyword = $_POST["txtKeyword"];
}
if(isset($_GET["txtKeyword"]))
{
$strKeyword = $_GET["txtKeyword"];
}
?>
<?php
$id=$_SESSION["id"];
$sql = "SELECT block.*, register.*
FROM block, register
WHERE block.block_by = '$id' AND register.id = block.block_to";
$query = mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($query);
$per_page = 8; **// Per Page Result to 1 **
$page = 1;
if(isset($_GET["Page"]))
{
$page = $_GET["Page"];
}
$prev_page = $page-1;
$next_page = $page+1;
$row_start = (($per_page*$page)-$per_page);
if($num_rows<=$per_page)
{
$num_pages =1;
}
else if(($num_rows % $per_page)==0)
{
$num_pages =($num_rows/$per_page) ;
}
else
{
$num_pages =($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$row_end = $per_page * $page;
if($row_end > $num_rows=$per_page)
{
$row_end = $num_rows;
}
$sql .= " ORDER BY block_id DESC LIMIT $row_start ,$row_end ";
$query = mysqli_query($conn,$sql);
$recordExists = 0;
?>
<?php
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
if($recordExists == 0 )
$recordExists = 1;
?>
//--- code image gallery -> https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox --- //
//----here is Result from mysql data base --- //
<?php
}
if($recordExists == 0 ){
echo "<div class='no_pending_int'>
<span>No blocked Member..!!</span>
</div>";
}
?>
<br>
<a class='precord'>Total Result : <?php echo $num_pages;?> Page's </a>
<br><br>
<?php
if($prev_page)
{
echo " <a class='pprev' href='$_SERVER[SCRIPT_NAME]?Page=$prev_page&txtKeyword=$strKeyword'>◄</a> ";
}
for($i = max(1, $page - 3); $i <= min($page + 3, $num_pages); $i++)
{
if($i != $page)
{
echo " <a class='numbers' href='$_SERVER[SCRIPT_NAME]?Page=$i&txtKeyword=$strKeyword'>$i</a> ";
}
else
{
echo "<b class='numberactive'>$i</b>";
}
}
if($page!=$num_pages)
{
echo " <a class='pprev' href ='$_SERVER[SCRIPT_NAME]?Page=$next_page&txtKeyword=$strKeyword'>►</a> ";
}
$conn = null;
?>
I have this couple queries, I am looking to making it run faster by creating a function like this. What would be the best way to do this? The queries find the tickets in the database that have been maintained
public function __select(){}
Below are the queries:
$data = array();
if($My_Privileges['User_Privilege'] >= 4 && $My_Privileges['Group_Privilege'] >= 4 && $My_Privileges['Other_Privilege'] >= 4){
$Tickets = array();
$r = sqlsrv_query($NEI,"
SELECT Elev.ID AS ID
FROM nei.dbo.Elev
LEFT JOIN nei.dbo.Loc ON Elev.Loc = Loc.Loc
WHERE Elev.Status = 0
AND Loc.Maint = 1
GROUP BY Elev.ID
;");
$data2 = array();
if($r){while($array = sqlsrv_fetch_array($r)){$data2[$array['ID']] = $array;}}
$sql = array();
foreach($data2 as $key=>$variable){$sql[] = "Elev.ID = '{$variable['ID']}'";}
$sql = implode(" OR ",$sql);
$r = sqlsrv_query($NEI,"
SELECT Max(TicketD.EDate) AS Last_Date,
Elev.ID AS ID
FROM nei.dbo.TicketD
LEFT JOIN nei.dbo.Elev ON TicketD.Elev = Elev.ID
LEFT JOIN nei.dbo.Job ON TicketD.Job = Job.ID
WHERE Job.Type = 0
AND ({$sql})
GROUP BY Elev.ID
;");
if($r){
while($array = sqlsrv_fetch_array($r,SQLSRV_FETCH_ASSOC)){
if(isset($data2[$array['ID']])){
$data2[$array['ID']]['Last_Date'] = $array['Last_Date'];
}
}
}
$r = sqlsrv_query($NEI,"
SELECT Elev.ID AS ID,
Elev.State AS State,
Elev.Unit AS Unit,
Elev.Type AS Type,
Loc.Tag AS Location,
Zone.Name AS Zone,
Emp.fFirst + ' ' + Emp.Last AS Route
FROM nei.dbo.Elev
LEFT JOIN nei.dbo.Loc ON Elev.Loc = Loc.Loc
LEFT JOIN nei.dbo.Zone ON Loc.Zone = Zone.ID
LEFT JOIN nei.dbo.Route ON Loc.Route = Route.ID
LEFT JOIN nei.dbo.Emp ON Route.Mech = Emp.fWork
WHERE Loc.Maint = 1
AND ({$sql})
;");
if($r){
while($array = sqlsrv_fetch_array($r,SQLSRV_FETCH_ASSOC)){
$array['Last_Date'] = substr($data2[$array['ID']]['Last_Date'],0,10);
$data[] = $array;
}
}
}
In another PHP file, I am creating a function called __select() and I have been trying to figure out the best way to condense the queries and make the website run faster. Any help would be appreciated.
Section 1
I have an issue in " Displaying 1 - 5 of 10 records ". I have a piece of code which works only on first page, when i click on second page then it show the same result " Displaying 1 - 5 of 10 records " Instead of " Displaying 10 of 10 records ".
Code In Controller
$total=$config["total_rows"];
$per_page=$config['per_page'];
$curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1);
$result_start = ($curpage - 1) * $per_page + 1;
if ($result_start == 0) $result_start= 1; // *it happens only for the first run*
$result_end = $result_start+$per_page-1;
if ($result_end < $per_page) // happens when records less than per page
{ $result_end = $per_page; }
else if ($result_end > $total) // happens when result end is greater than total records
{ $result_end = $total;}
$data['show']="displaying $result_start to $result_end of $total";
I don't know whats wrong with it, I have tried other code which I find from different websites, but they are not working properly.
Section 2
I have a filter section, where user can filter product by Size, Color and Price,
How to achieve this section?
My main/ Index Controller
public function index($page=1)
{
$config = array();
$keyword = $this->input->post('search');
if ($keyword === null){ $keyword = $this->session->userdata('search');}
else{ $this->session->set_userdata('search',$keyword);}
$config["base_url"] = base_url();
$config["total_rows"] = $this->crt->total_items($keyword);
$config['use_page_numbers'] =true;
$config['cur_tag_open'] = '<a class="page-numbers current">';
$config['cur_tag_close'] = '</a>';
$config["per_page"] =5;
$config["uri_segment"] = 1;
$this->pagination->initialize($config);
$page = ($page - 1) * $config['per_page'];
// showing x to y of z records
$total=$config["total_rows"];
$per_page=$config['per_page'];
$curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1);
$result_start = ($curpage - 1) * $per_page + 1;
if ($result_start == 0) $result_start= 1; // *it happens only for the first run*
$result_end = $result_start+$per_page-1;
if ($result_end < $per_page) // happens when records less than per page
{ $result_end = $per_page; }
else if ($result_end > $total) // happens when result end is greater than total records
{ $result_end = $total;}
$data['show']="displaying $result_start to $result_end of $total";
$data['sidebar']=$this->crt->sidebar_cat();
$data['products']=$this->crt->get_product($config["per_page"], $page,$keyword);
$data["links"] = $this->pagination->create_links();
$this->load->view('header');
$this->load->view('index',$data);
$this->load->view('footer');
}
My Model
// Paginitions for Items
function total_items($keyword)
{
//return $this->db->count_all("product");
$this->db->like('product_name',$keyword);
$this->db->from('product');
return $this->db->count_all_results();
}
//Fetching Products
public function get_product($limit,$start,$keyword){
// $this->db->where('Is_Hidden',0);
// $this->db->select('*');
// $this->db->from('product');
$this->db->order_by('product_id', 'DESC');
$this->db->limit($limit, $start);
$this->db->like('product_name',$keyword);
$query = $this->db->get_where('product');
if(!$query->num_rows()>0)
{
echo '<h1>No product available</h1>';
}
else
{
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
}
How I can get the Filter section?
UPDATE 1
Section 1 issue has been fixed by replacing those two lines
$curpage=floor(($this->uri->segment(1)/$config['per_page']) + 1);
if ($result_start == 0) $result_start= 1; //
TO
$curpage=$this->uri->segment(1);
if ($result_start == 0 || $result_start<0) $result_start= 1; //
Update 2
I somehow did the filter section but now I am stuck in the ajax issue. Issue is that When color or size checkbox is empty then it throw error of foreach loop.
I only need to control the empty or null section, like if the checkbox is unchecked then it will not send / post the value to the controller...
My Ajax Code is
function clr(){
var selected = new Array();
var size = new Array();
var url="<?php echo base_url('Cart/filt_color');?>";
// alert(url);
$("input:checkbox[name=color]:checked").each(function() {
selected.push($(this).val());
//console.log(selected);
});
// Sizes
$("input:checkbox[name=size]:checked").each(function() {
size.push($(this).val());
//console.log(selected);
});
$.ajax({
url:url,
method:"post",
data:{'colors':selected,'sizes':size},
success:function(data)
{
//
//console.log(data);
$("#mdv").html(data);
}
});
}
I have tried many check like, undefined, or =='' or data.length <-1 etc. The data.length will did some check but i am not able to check the variable separately like, there are two variable I am send in data: color,size How can I check the variable separately like: if(data.color.length < 0 ) .
When you initialize the pagination config try to use the the controller/method in $config[base_url] and get the page number from $this->uri->segment(3)
Answered is Here, All the details and code are posted in the mentioned link question.
I have some code in jquery that connects to php and refreshes the class with latest data. This is working ok. However, I need to update 3 classes and when it refreshses the values are empty.
Is there a way I can query db and update 3 classes with fresh data every n sec. Many thanks
js
// Update server with latest actions,destructions and return requests
setInterval(function() {
$.get('/domain/admin/refreshBox.php', function(data) {
$(".actions").text(data);
$(".retrievals").text(data);
$(".returns").text(data);
});
}, 10000);
php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
//echo $num;
$ni = $num;
if($ni < 1) {
$ni = '0';
}
echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as ni FROM act WHERE activity='New Intake' AND new = '1'");
$niintknum_row = mysqli_fetch_assoc($nisql);
$niintknum = $niintknum_row['ni'];
//echo $num;
$niintk_num = $niintknum;
if($niintk_num < 1) {
$niintk_num = '0';
echo $niintk_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as rtrv FROM act WHERE activity='Box Retrieval' AND new = '1'");
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['rtrv'];
//echo $num;
$brtv_num = $brtvnum;
if($brtv_num < 1) {
$brtv_num = '0';
echo $brtv_num;
$brtnsql= mysqli_query($conn,"SELECT count(*) as brtn FROM act WHERE activity='Box Return' AND new = '1'");
$brtn_row = mysqli_fetch_assoc($brtnsql);
$brtnnum = $brtn_row['brtn'];
//echo $num;
$brtn_num = $brtnnum;
if($brtn_num < 1) {
$brtn_num = '0';
}
echo $brtn_num;
I have problem when a visitor clicks on a submenu and the link opens in a new page, so I want to keep that submenu active on that page.
I have css class active and javascript for opening it, what I need is to make it with php to be active.
This is UL with class:
This is my code. Can it be done with php or with javascript.
<ul>
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?=$emrikategorise;?>
<ul>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");
$rPrind = mysqli_query($dbc,$qPrind);
while($prind = mysqli_fetch_array($rPrind)) {
?>
<li><?=$prind['kemri']?> </li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php }
mysqli_free_result($rKategori);
}
?>
</ul>
You can see menu on the left in The website is www.sitimobil.mk
You probably will need to build the array before outputting to be able to determine which menus should be active. You can also combine it with an optimization of the query to not have to do 1 query per category.
Something like:
$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$id = $exKat['kid'];
//To prevent numerical array with unused space
$name = 'kategori'.$exKat['kid'];
$list[$name] = $exKat;
//Calculate depth to see if the menu is a sub..sub..sub menu etc.
$parent = $list[$name]['kprind'];
if($parent == 0) {
$list[$name]['depth'] = 0;
$list[$name]['childCount'] = 0;
}
else {
$list['kategori'.$parent]['childCount']++;
$list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
}
if($id == $active) {
$list[$name]['active'] = true;
while($parent != 0) {
$parentName = 'kategori'.$parent;
$list[$parentName]['active'] = true;
$parent = $list[$parentName]['kprind'];
}
}
else
$list[$name]['active'] = false;
}
mysqli_free_result($rPrind);
//Once we have that we can output the results...
function output_menu($list, $parent = 0, $active = false)
$activeClass = $active ? ' class="active"' : '';
echo '<ul'.$activeClass.'>';
foreach($list as $row){
if($row['kprind'] != $parent) continue;
$link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
echo '<li>'.$row['kemri'].'';
if($row['childCount'] > 0)
output_menu($list, $row['kprind'], $row['active']);
echo '</li>';
}
echo '</ul>';
}
output_menu($list);
}
This is still a bit rough but should do the trick. It can probably be optimized so that we don't have to go through the list too many times but has the benefit of not having to request too many calls to the database. That should result in a lighter workload for the DB and faster output.