I am retrieving data from mysql and need to display the result in a specific class. I am using jquery to update every 10 seconds and this is working ok. Where I am getting stuck is getting that data into a specific class: actions.
I would be grateful if someone could point me in the right direction? php or jquery will be acceptable. Many thanks
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
$ni = $num;
if($ni < 1) {
$ni = '0';
} else {
echo $ni; <--- NEED TO LOAD RESULT IN ACTIONS CLASS
}
Example html from header.php
<li>
Boxes <span class="drop-icon">▸</span> <label class="drop-icon" for="sm4" title="Toggle Drop-down">▾</label>
<input id="sm4" type="checkbox">
<ul class="sub-menu">
<li>
New Intake <span style="float: right;" class="notification ni"><?php echo $ni_num; ?></span>
</li>
<li>
Retrievals <span style="float: right;" class="notification retrievals"><?php echo $brtv_num; ?></span>
</li>
<li>
Returns <span style="float: right;" class="notification returns"><?php echo $brtn_num; ?></span>
</li>
<li>
Destructions <span style="float: right;" class="notification destructions"><?php echo $bdstr_num; ?></span>
</li>
<li>
Permanent Retrieval <span style="float: right;" class="notification pretrieval"><?php echo $prtv_num; ?></span>
</li>
</ul>
</li>
Example from loadActions.php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
$ni = $num;
if($ni < 1) {
$ni = '0';
} echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as intake FROM act WHERE activity='New Intake' AND new = '1'"); // provide db connection object as first parameter
$ni_row = mysqli_fetch_assoc($nisql);
$ninum = $ni_row['intake'];
//echo $num;
$ni_num = $ninum;
if($ni_num < 1) {
$ni_num = '0';
} echo $ni_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as brtv FROM act WHERE activity='Box Retrieval' AND new = '1'"); // provide db connection object as first parameter
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['brtv'];
//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'"); // provide db connection object as first parameter
$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;
Please note, I am NOT a PHP programmer so you will have to do some work yourself
Take below as pseudo code and ask another PHP question if the PHP does not make sense.
Have ONE request
select activity,
count(*) total,
sum(activity = 'New Intake') intakeCount,
sum(activity = 'Box Retrieval') boxCount,
...
from act WHERE new = '1'
if ($rec["total"] == 0) {
echo '{ "total" : 0 }';
die 0;
}
$res = array(
"total" => $rec["total"],
"ni" => $rec["intakeCount"],
"retrievals" => $rec["boxCount"],
...
);
echo json_encode($res);
Result should be
{ "total" : 24,
"ni" : 14,
"retrievals" : 9,
....
}
Then you can do
function getBoxes() {
$.get('/domain/admin/loadActions.php', function(data) {
processData(data);
setTimeout(getBoxes, 15000);
});
}
function processData(data) {
for (key in data) {
console.log(key,data[key])
$("." + key).text(data[key]);
}
}
$(function() { // page load
// testing - remove this when running the getBoxes():
processData({
"total": 24,
"ni": 14,
"retrievals": 9
});
// getBoxes(); // remove comment when tested
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
Boxes <span class="drop-icon">▸</span> <label class="drop-icon" for="sm4" title="Toggle Drop-down">▾</label>
<input id="sm4" type="checkbox">
<ul class="sub-menu">
<li>
New Intake <span style="float: right;" class="notification ni"></span>
</li>
<li>
Retrievals <span style="float: right;" class="notification retrievals"></span>
</li>
<li>
Returns <span style="float: right;" class="notification returns"></span>
</li>
<li>
Destructions <span style="float: right;" class="notification destructions"></span>
</li>
<li>
Permanent Retrieval <span style="float: right;" class="notification pretrieval"></span>
</li>
</ul>
</li>
<div class="total"></div>
Related
I have a page which allows you to filter results using an AJAX call which works fine, I have added pagination which work fine initially but as soon as you move to another page, the checkbox becomes unchecked and it just shows all results again. I assume this is because the page is reloading when it moves to page 2, is there a way of keep the filter setting set and continue to show the results from the filter AJAX. The pagination obvisouly works fine when no filter is selected but my brain just doesn't seem to be working and can't work this out.
Any help would be appreciated!
My code is below, I am also aware that currently my code is open to sql injection but just trying to get everything to work and then will go back through it:
<body>
<?php include("PHP/header.php"); ?>
<div class="container-fluid">
<div class="container" style="margin-top: 2%; text-align: center;">
<h1> Reviews</h1>
On This page you will find our reviews on music tech and software
<br/>
<br/>
<br/>
Filter Reviews:
<ul class="list-group">
<?php
$search = $conn->prepare("SELECT DISTINCT reviewcat FROM review_db ORDER BY reviewcat");
$search->execute();
while ($row = $search->fetch(PDO::FETCH_ASSOC)) {
?>
<li class="list-group-item">
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input product_check" value="<?=$row['reviewcat'];?>" id="reviewcat"> <?=$row['reviewcat']; ?>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
<br/><br/>
<div class="row-fluid ">
<h5 class="text-center" id="textChange"> All Reviews </h5>
<hr>
<div class="text-center">
<img src="Images/loader.gif" id="loader" width="100" style="display: none">
</div>
<?php
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 8;
$offset = ($pageno-1) * $no_of_records_per_page;
// Prev + Next
$prev = $pageno - 1;
$next = $pageno + 1;
?>
<div id="result" class="card-deck card_group_style pt-4" >
<?php
$stmt = $conn->prepare("SELECT COUNT(*) FROM review_db");
$stmt->execute();
$total_rows = $stmt->fetchColumn();
$total_pages = ceil($total_rows / $no_of_records_per_page);
$result = $conn->prepare("SELECT * FROM review_db ORDER BY reviewsub DESC LIMIT $offset, $no_of_records_per_page ");
$result->execute();
?>
<?php while ($row = $result->fetch(PDO::FETCH_ASSOC)) {// Important line !!! Check summary get row on array .. ?>
<?php
$my_date = $row['reviewsub'];
$date = DATE("d/m/Y",strtotime($my_date));
?>
<div class="col-sm-6 col-lg-3 py-2">
<div class="card mb-4">
<img class="card-img-top card-images " src="Images/Reviews/<?php echo $row['reviewimage1'];?>" alt="<?php echo $row['reviewtitle'];?>" >
<div class="card-body">
<h5 class="card-title"><?php echo $row['reviewtitle'];?></h5>
<p class="card-text"><?php echo $row['reviewsynop'];?></p>
<a href="Reviews/review-content.php?id=<?php echo $row['id'];?>&reviewtitle=<?php echo $row['reviewtitle'];?>" class="btn btn-primary my-4" >Read More</a>
<div class="card-footer" style="padding: 1%;">
<small class="text-muted">Submitted: <?php echo $date; ?></small>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
<div class="container">
<!-- Pagination Controller -->
<?php
if($total_pages <= 1){
$hidepage = 'none';
}else{
$hidepage = 'flex';
}
?>
<ul class="pagination justify-content-center pagination-mb" style="display: <?php echo $hidepage; ?>">
<li><a class="page-link" href="?pageno=1">First</a></li>
<li class="page-item <?php if($pageno <= 1){ echo 'disabled'; } ?>">
<a class="page-link" href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
</li>
<?php for($i = 1; $i <= $total_pages; $i++ ): ?>
<li class="page-item <?php if($pageno == $i) {echo 'active'; } ?>">
<a class="page-link" href="?pageno=<?= $i; ?>"> <?= $i; ?> </a>
</li>
<?php endfor; ?>
<li class="page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
<a class="page-link" href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
</li>
<li><a class="page-link" href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
</ul>
<!-- Pagination end -->
</div>
</div>
</div>
</div>
<?php include("PHP/footer.php"); ?>
</div>
</body>
<?php include("PHP/js.php"); ?>
<script>
$(document).ready(function(){
$('#link-review,#link-footer-review').addClass('active');
});
</script>
<script type="text/javascript">
$(document).ready(function(){
function get_filter_text(text_id){
var filterData = [];
$('#'+text_id+':checked').each(function(){
filterData.push($(this).val());
});
return filterData;
}
$(".product_check").click(function(){
if ($(this).prop('checked')) {
$("#loader").show();
var action = 'data';
var reviewcat = get_filter_text('reviewcat');
$.ajax({
method:'POST',
url:'reviewaction.php',
data:{action:action,reviewcat:reviewcat},
success:function(response){
$("#result").html(response);
$("#loader").hide();
$("#textChange").text("Filtered Reviews");
}
});
} else {
$("#loader").show();
var action = 'data';
var reviewcat = get_filter_text('reviewcat');
$.ajax({
method:'POST',
url:'reviewaction.php',
data:{action:action,reviewcat:reviewcat},
success:function(response){
$("#result").html(response);
$("#loader").hide();
$("#textChange").text("All Reviews");
}
});
}
});
});
</script>
reviewaction.php:
<?php
if(isset($_POST['action'])){
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 8;
$offset = ($pageno-1) * $no_of_records_per_page;
// Prev + Next
$prev = $pageno - 1;
$next = $pageno + 1;
$checksql = "SELECT COUNT(*) FROM review_db WHERE reviewcat !=''";
$sql = "SELECT * FROM review_db WHERE reviewcat !=''";
if(isset($_POST['reviewcat'])){
$reviewcat = implode("','", $_POST['reviewcat']);
$checksql .="AND reviewcat IN('".$reviewcat."')";
$sql .="AND reviewcat IN('".$reviewcat."')";
}
$resultpag = $conn->prepare($checksql);
$resultpag->execute();
$total_rows = $resultpag->fetchColumn();
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql .="ORDER BY reviewsub DESC LIMIT $offset, $no_of_records_per_page ";
$result = $conn->prepare($sql);
$result->execute();
$output='';
if (count($result) > 0) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$my_date = $row['reviewsub'];
$date = DATE("d/m/Y",strtotime($my_date));
$output .= '
<div class="col-sm-6 col-lg-3 py-2">
<div class="card mb-4">
<img class="card-img-top card-images" src="Images/Reviews/'.$row['reviewimage1'].'" alt="'.$row['reviewtitle'].'" >
<div class="card-body">
<h5 class="card-title">'.$row['reviewtitle'].'</h5>
<p class="card-text">'.$row['reviewsynop'].'</p>
<a href="Reviews/review-content.php?id='.$row['id'].'&reviewtitle='.$row['reviewtitle'].'" class="btn btn-primary my-4" >Read More</a>
<div class="card-footer" style="padding: 1%;">
<small class="text-muted">Submitted: '.$date.'</small>
</div>
</div>
</div>
</div>
';
} //While Loop End
}else{
$output = "<h3>No Reviews Found!</h3>";
}
echo $output;
}
?>
You can do it a couple of ways. One is to add the filter to the GET URI parameters of each page link at the end of your filter function, and add code that marks the filters as selected/checked if the parameters exist in the URI before running the POST request. The other is to change the code so that pagination is done with the same POST request instead of actually navigating to a new URL.
I'm working on a dropdown menu that is items are rows from a table called notifications each row has a type column and each type have a specific output ( echo ) so to output every row as an item in the menu I looped for each item in the MySQL Array but when I do those items shows in the dropdown menu but they are empty like this:-
Code:-
// notifications function here //
// unreaded notifications count to echo in the bootstrap4 badge //
$unreadednotifications = "SELECT * from `notifications` where `status` = 'unread' order by `date` DESC";
$unreadedcount = count(fetchAll($unreadednotifications));
// all notifications to sort in the dropdown menu //
$notifications = "SELECT * FROM `notifications` WHERE accountid = '8' ORDER BY `date` DESC";
$notificationscount = count(fetchAll($notifications));
// notification function ends here//
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="notificationsdrop" onclick="badgefade()" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div style="font-size: 12px;"><i class="fa fa-bell fa-3x bell" aria-hidden="true"></i><?if($unreadedcount > 0){echo'<span class="badge badge-notify" id="notificationsBadge" style="font-size:15px;">'.$unreadedcount.'</span>';}?></div></a>
<div class="dropdown-menu notifications" aria-labelledby="notificationsdrop">
<? if(count(fetchAll($notifications)) > 0){
foreach(fetchAll($notifications) as $i){
?>
<a class="dropdown-item" href="view.php?id=<?php echo $i['id'] ?>" style="<? if($i['status']==['unread']){
echo"font-weight:bold;";
}?>">
<?
if ($i['type']==['socialalert']){
echo'Someone Followed You';
}
?>
</a>
<?}}?>
</div>
</li>
update : added function.php:-
function fetchAll($query){
$con = new PDO(DBINFO, DBUSER, DBPASS);
$stmt = $con->query($query);
return $stmt->fetchAll();
}
function performQuery($query){
$con = new PDO(DBINFO, DBUSER, DBPASS);
$stmt = $con->prepare($query);
if($stmt->execute()){
return true;
}else{
return false;
}
}
?>
Fixed: I forget that the equal value for if statement must be like this.
if ($i['type']=='socialalert'){
echo'Someone Followed You';
}
I'm currently working on a page that calls a mySQL database to populate a list of members. However, I need that list to be split into two equal parts, so that half can float to the left and half to the right. However, I have beat this horse to death and still cannot figure out how to split the array.
Here's what I have currently:
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
if ( $rowcount > 0 ) { ?>
<div class="members-left">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
</div>
However, I want the output to look something like this (let's say my table has 10 members):
<div class="holder">
<!--output first half of members from table: -->
<div class="members-left">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
<!--output second half of members from table: -->
<div class="members-right">
<ul class="members">
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
<li class="member">...</li>
</ul>
</div>
</div>
I've tried setting counters and using things like if($i <= $rowcount/2), but to no avail. Any help would be greatly appreciated—I'm very new to mySQL and have limited knowledge of PHP, so this one has me stumped.
add a control variable like "$i". add +1 to $i every loop. and check if $i reached half of number of rows. if reached close ul and div and open new div and ul and set $i to 0
<div class="holder">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i=0;
if ( $rowcount > 0 ) { ?>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
//SOME CONTENT HERE
</li>
<?php
$i++;
if($i>=($rowcount/2)){
echo '</ul></div>
<div class="members-right">
<ul class="members">';
$i=0;
}
} ?>
</ul>
</div>
<?php } ?>
</div>
You could use a for loop for the first half and just finish the second half with a while loop that goes until there are no more results.
First half:
for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++)
Second half
while ($row = $members->fetch_assoc())
Example with HTML
<div class="members-left">
<ul class="members">
<?php for($i = 0; $i <= $rowcount/2 && $row = $members->fetch_assoc(); $i++) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
<div class="members-right">
<ul class="members">
<?php while ($row = $members->fetch_assoc()) { ?>
<li class="member">
// do something with $row
</li>
<?php } ?>
</ul>
</div>
I would recommend you to make 2 arrays of your members and then print them out. The advantage is you will have more control of the members and your code will be more readable for later use;
<?php
$i =0;
while ($row = $members->fetch_assoc()) {
if($i % 2 == 0)
{
$right_members[] = $row;
}
else
{
$left_members[] = $row;
$i++;
}
echo '
<div class="members-right">
<ul class="members">';
foreach($right members as $r_member){
echo '<li class="member">...</li>';
}
echo '
</ul>
</div>';
//SAME WITH LEFT MEMBERS
?>
Having a counter was an idea, I will not debate on having model logic in view ;)
well, a solution would be :
<div class="holder">
<div class="members-column">
<ul class="members">
<?php
$members = $db->query('SELECT * FROM tableContacts ORDER BY lastName ASC');
$rowcount = mysqli_num_rows($members);
$i = 0;
while ($row = $members->fetch_assoc()) {
?>
<li class="member">
//SOME CONTENT HERE
</li>
<?
// Check if current row is the 'middle count', creating a new column
if ($i === ceil($rowcount / 2)) : ?>
</ul>
</div>
<div class="members-column">
<ul class="members">
<?php endif; ?>
<?php
$i++;
}
?>
</ul>
</div>
</div>
my code is suppose to display multiple movies. However, it is only displaying ONE movie. I know I'm suppose to tell you what I've tried. I've moved code, checked the db, but nothing has changed. The code used to work, but I added some new code and the code is now not working. I then deleted the new code but the problem continued. I have a lot of code and realize this question will just be deleted. This is all I'm asking: If you see something weird, comment on it.
Note: I promise there is no background with the db information and that there is more than one row of information in the db. Thanks!
movies.php
<?php
error_reporting(0);
require "start.php";
require "dropbox_auth.php";
session_start();
if(!$_SESSION["id"]) {
header("location: index.php");
}
$id2 = $_SESSION["id"];
$name = $_GET["name"];
$name2 = $_GET["name2"];
$db2 = new mysqli("127.0.0.1", "root", "", "crave crap");
$one2 = $db2->query("SELECT * FROM users WHERE id='$id2'");
$two2 = $one2->fetch_object();
$three2 = $two2->username;
$four2 = $two2->premium;
if(isset($name)) {
$findName = $db2->query("SELECT * FROM movies WHERE id='$name'");
$fetchName = $findName->fetch_object();
$real_title = $fetchName->title;
echo "<div id='notVerifiedDiv'> <span id='notVerifiedText'> <strong> $real_title </strong> added to liked movies </span> </div> </div>";
$page = $_GET["page"];
$sorting = $_GET["sorting"];
header("Refresh:1; url=http://localhost/Drop%20Box/movies.php?page=".$page."&sorting=".$sorting);
}
if(isset($name2)) {
$findName2 = $db2->query("SELECT * FROM movies WHERE id='$name2'");
$fetchName2 = $findName2->fetch_object();
$real_title2 = $fetchName2->title;
echo "<div id='notVerifiedDiv'> <span id='notVerifiedText'> <strong> $real_title2 </strong> removed from liked movies </span> </div> </div>";
$page = $_GET["page"];
$sorting = $_GET["sorting"];
header("Refresh:1; url=http://localhost/Drop%20Box/movies.php?page=".$page."&sorting=".$sorting);
}
if(!$four2) {
// They are not premium
header("location: premium.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Movies </title>
<link rel="stylesheet" href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css">
<link rel='stylesheet' href='main.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='main.js'></script>
</head>
<body>
<!-- Navigation -->
<div id='nav'>
<!-- Profile Wrapper -->
<ul class="profile-wrapper">
<li>
<!-- user profile -->
<div class="profile">
<img src="avatars/default.png" />
<?php echo $three2; ?> <i class="fa fa-caret-down" id="caret-down"></i>
<!-- more menu -->
<ul class="menu">
<li>Sign Out</li>
<li>Sign Out</li>
<li>Sign Out</li>
</ul>
</div>
</li>
</ul>
<!-- End of Profile Wrapper -->
</div>
<!-- End of Navigation -->
<!-- Movie Content -->
<div id='movie_content2'>
<div id='movie_line'>
<div id='movie_line2'></div>
<!-- Dropdown Selection -->
<?php
$sorting = $_GET["sorting"];
$page = $_GET["page"];
if($sorting == "") {
header("location: http://localhost/Drop%20Box/movies.php?page=1&sorting=recent");
}
if($sorting == "recent" || $sorting !== "popular" && $sorting !== "history" && $sorting !== "likes") {
echo '<nav>
<ul id="dropdown_selection">
<li>Most Recent
<ul>
<li> Most Liked </li>
<li> My History </li>
<li> My Likes </li>
</ul>
</li>
</ul>
</nav>';
}
if($sorting == "popular") {
echo '<nav>
<ul id="dropdown_selection">
<li>Most Liked
<ul>
<li> Most Recent </li>
<li> My History </li>
<li> My Likes </li>
</ul>
</li>
</ul>
</nav>';
}
if($sorting == "history") {
echo '<nav>
<ul id="dropdown_selection">
<li>My History
<ul>
<li> Most Recent </li>
<li> Most Liked </li>
<li> My Likes </li>
</ul>
</li>
</ul>
</nav>';
}
if($sorting == "likes") {
echo '<nav>
<ul id="dropdown_selection">
<li>My Likes
<ul>
<li> Most Recent </li>
<li> Most Liked </li>
<li> My History </li>
</ul>
</li>
</ul>
</nav>';
}
?>
<!-- End of Dropdown Selection -->
<?php
// Pagination
$per_page = 10;
$count_total = $db2->query("SELECT * FROM movies");
$pages = $count_total->num_rows;
$total_pages = ceil($pages / $per_page);
if(!isset($_GET["page"])) {
header("location: movies.php?page=1");
} else {
$page = $_GET["page"];
}
$start = (($page - 1) * $per_page);
$sorting = $_GET["sorting"];
if($sorting == "recent" || $sorting !== "popular" && $sorting !== "history" && $sorting !== "likes") {
$movie = $db2->query("SELECT * FROM movies LIMIT $start, $per_page");
}
if($sorting == "popular") {
$movie = $db2->query("SELECT * FROM movies ORDER BY likes DESC LIMIT $start, $per_page");
}
session_start();
$id3 = $_SESSION["id"];
if($sorting == "history") {
$movie = $db2->query("SELECT m.id AS mid,m.photo AS pho, m.destination AS des,m.length AS len,m.length_content AS lenc,m.description AS desa,m.rating AS rat FROM movies m INNER JOIN history h ON h.movie_id = m.id WHERE h.user_id = $id3 ORDER BY h.id LIMIT $start, $per_page");
}
if($sorting == "likes") {
$movie = $db2->query("SELECT * FROM movies m INNER JOIN likes h ON h.number_likes = m.id WHERE h.user = $id3 ORDER BY h.id LIMIT $start, $per_page");
}
$number = 0;
$fetch_movie = $movie->num_rows;
if($fetch_movie > 0) {
while($movie3 = mysqli_fetch_array($movie)) {
$number++;
if($sorting !== "history") {
$id2 = $movie3["id"];
$photo = $movie3["photo"];
$rating = $movie3["rating"];
$destination = $movie3["destination"];
$length = $movie3["length"];
$length_content = $movie3["length_content"];
$description = $movie3["description"];
} else {
$id2 = $movie3["mid"];
$photo = $movie3["pho"];
$destination = $movie3["des"];
$length = $movie3["len"];
$length_content = $movie3["lenc"];
$description = $movie3["desa"];
$rating = $movie3["rat"];
}
$sorting = $_GET["sorting"];
$findLike = $db2->query("SELECT * FROM likes WHERE number_likes='$id2'");
$numLike = $findLike->num_rows;
echo "<div id='descriptive_div' number='$number'> <i class='fa fa-caret-left' id='descriptive_caret' number='$number'></i> <a href='like.php?number=$id2&page=$page'>";
$sorting = $_GET["sorting"];
if($sorting !== "likes") {
if($numLike == 0) {
// Not Liked
echo "<a href='like.php?number=$id2&page=$page&code=1&sorting=$sorting'> <div class='like_button' number='$number'> Like </div> </a>";
} else {
echo "<a href='like.php?number=$id2&page=$page&sorting=$sorting'> <div class='liked_button' number='$number'> Like </div> </a>";
}
} else if($sorting == "likes") {
echo "<a href='like.php?number=$id2&page=$page&sorting=$sorting'> <div class='liked_button' number='$number'> Like </div> </a>";
}
echo "</a> <span id='descriptive_div_text'> $description </span> </div>";
if($length_content) {
// hr & min
echo "<a href='open.php?destination=$destination'> <div class='movie_length' number='$number'> <div id='movie_length_text' number='$number'> $length </div> </div> </a>";
} else {
// min
echo "<a href='open.php?destination=$destination'> <div class='movie_length2' number='$number'> <span id='movie_length_text' number='$number'> $length </span> </div> </a>";
}
$sorting = $_GET["sorting"];
if($rating == "PG-13") {
if($sorting !== "likes") {
if($numLike == 0) {
// Not Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
} else {
// Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating4' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
}
} else if($sorting == "likes") {
// Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating4' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
}
}
if($rating == "PG") {
if($sorting !== "likes") {
if($numLike == 0) {
// Not Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating2' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
} else {
// Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating5' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
}
} else if($sorting == "likes") {
// Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating5' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
}
}
if($rating == "G" || $rating == "R") {
if($sorting !== "likes") {
if($numLike == 0) {
// Not Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating3' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
} else {
// Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating6' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
}
} else if($sorting == "likes") {
// Liked
echo "<a href='open.php?destination=$destination'> <div class='movie_rating6' number='$number'> <span id='movie_rating_text' number='$number'> $rating </span> </div> </a>";
}
}
}
if($numLike) {
// Liked
echo "<a href='open.php?destination=$destination'> <img src='$photo' class='movie_size3' number='$number'> </a>";
} else {
// Not Liked
echo "<a href='open.php?destination=$destination'> <img src='$photo' class='movie_size' number='$number'> </a>";
}
} else {
echo "No Movies to Display";
}
if($fetch_movie !== 0) {
echo "<br>";
for($number=1;$number<=$total_pages;$number++) {
if($page == $number) {
echo '<div class="complete_page">'.$number.'</div>';
} else {
$sorting = $_GET["sorting"];
echo ' <div class="number_page">'.$number.'</div>';
}
}
}
?>
</div>
</div>
<!-- End of Movie Content -->
</body>
</html>
UPDATE
One thing to note is that the ONE movie is from the results of the LAST row in the db and not the FIRST row in the db. Usually, the information only comes from the FIRST db if there is a problem with the while loop. What does it mean if the ONE movie is coming from the last row in the db? I'm trying to provide more info so users can have a better understanding of how to solve this problem...
I have provided an image of my project:
These are some spots for improvement
always put session_start() as the first thing in code, those includes later may use sessions and your code will fail – Muhammed M. just now edit
$name = $_GET["name"]; $name2 = $_GET["name2"]; make sure they are set, replace like this: $name=isset($_GET['name'])? $_GET['name']:''; if $_GET['name'] is set, you will have it in $name, otherwise $name will be empty string ''. Do this for all $_GET, $_POST, or any other variable you just assume it is there, when in fact it might not be.
Try separating HTML from PHP harder. At least you could do is have all PHP related code on top, even if its' foreach that constructs your table, assign it in a variable, and include in you html. Better to have two files: main.php, main_html.php, you get it, something like this.
You have header() after echo(), it won't work, will give error. header() must be called before any output. Move all of your if(..) { header()} to the top of the page. That redirection logic should be the first in your code.
There are other things, but I feel like these are the most critical at this point for you.
And one more thing - please look at other's code, learn how to code properly, and you will love PHP for that. Don't look at some junky code and blame PHP. Download well known PHP frameworks for instance, dig inside learn what PSR-0, PSR-1... etc are. These all will help you become a better coder. And yes - don't give up! Many many years of PHP behind my back, but I am still learning every day ))
this is the controller method
public function ajaxLoad()
{
$data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
$data['content'] = $this->load->view('item', $data, true);
$data = json_encode($data);
echo $data;
}
and this is the js that invokes ajax
var tempScrollTop, currentScrollTop = 0;
$(document).scroll(function(){
currentScrollTop = $(document).scrollTop();
if (tempScrollTop < currentScrollTop )
{
var result = currentScrollTop % 100;
if(result == 0)
{
$.ajax({
url: "ajax/load",
type: "POST",
success: function(res){
$("#content").html(res);
}
});
}
}
else if (tempScrollTop > currentScrollTop )
{
var result = currentScrollTop % 100;
if(result == 0)
{
$("#content").text("Вверх запрос " + result);
}
}
tempScrollTop = currentScrollTop;
})
the problem i that i can't get the part of a page with the query that goes in the content and then json_encode to transfer to javascript, if i remove the
$data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
and change this to
$data['content'] = $this->load->view('item', null, true);
thus without the $data object its ok.
then its comes empty, but i need the database rows to display in the content
how can i solve this problem??
and the echo $data; - its the only way to transfer the data to js??, i tried return $data;, but that doesn't work :(
and also the main problem is that the PHP generates the page with the foreach function that generates records by loop, but if i put one of those records with ajax will the variables inside that partial become values of the database query??, or i need to set the values with js??
i am confused about that, sorry if i am wrong, can you help me???
so this is how looks the page generated by php by when the pages loads:
<? $i = 1 ?>
<? foreach($query->result() as $q): ?>
<?
$milliseconds = $q->end;
//echo $dd;
//echo time();
/*
$year = date('y', $t);
$month = date('m', $t);
$day = date('d', $t);
$hour = date('h', $t);
$minute = date('i', $t);
$second = date('s', $t);
*/
$d = new Datecalc;
$begin = date("Y-m-d H:i:s");
$end = date($q->end);
#$date = $d->dateDiff($begin , $end);
//$begin = strtotime($begin);
//$end = strtotime($q->end);
$d->dateDiff($begin, $end);
//echo $d->day;
$desc = substr($q->desc, 0, 225);
if(strlen($desc) > 180)
{
$desc = $desc."...";
}
?>
<input type="hidden" value="<?= $milliseconds ?>" id="milliseconds_<?= $q->id ?>" />
<div class="item" id="item_<?= $q->id ?>">
<? if(!empty($_SESSION['role']) && $_SESSION['role'] == 'admin'): ?>
<div class="admin_delete">
<?= img('css/img/admin_delete.png'); ?>
</div>
<? endif; ?>
<div class="desc">
<span class="discount">Скидка <?= $q->discount ?>%</span>
<span class="desc"><?= $desc ?></span>
</div>
<div class="item_pic">
<? $attr = array('src' => $q->image,
'id' => 'item_pic',
'class' => 'item_pic') ?>
<?= img($attr) ?>
</div>
<div class="menu_3">
<ul class="menu_3">
<li class="timer">
<? $attr = array('src' => 'css/img/time.png',
'class' => 'time') ?>
<?= img($attr) ?>
<span id="days_<?= $q->id?>"><?= $d->day ?></span>д.
<span id="hours_<?= $q->id?>"><?= $d->hour ?></span> :
<span id="minutes_<?= $q->id?>"><?= $d->min ?></span> :
<span id="seconds_<?= $q->id?>"><?= $d->sec ?></span>
</li>
<li class="price">
<?= $q->price ?>с.
</li>
<li class="buy">
<div class="small">
99
</div>
<a href="<?= base_url() ?>buy/<?= $q->id ?>">
<?= img('css/img/kupit.png') ?>
</li>
<li class="item_arrow">
<?= img('css/img/item_arrow.png') ?>
<? if($i % 2 == 0): ?>
<ul class="submenu2">
<? else: ?>
<ul class="submenu2">
<? endif; ?>
<li>
<a href="<?= base_url() ?>show/<?= $q->id ?>">
Подробнее
</a>
</li>
<li>
Как это работает
</li>
<li style="border-bottom: none;">
Рассказать друзьям
</li>
<li style="border-bottom: none;">
<?= img('css/img/namba.png') ?>
<?= img('css/img/mail_ru.png') ?>
<?= img('css/img/odnoklassniki.png') ?>
<?= img('css/img/vkontakte.png') ?>
<?= img('css/img/facebook.png') ?>
</li>
</ul>
</li>
</ul>
</div>
</div>
<? $i++; ?>
<? endforeach; ?>
<div class="clear"></div>
i dont know how to put the records by ajax separately gradualy when the user scrolls down
Try rewriting these two lines
$data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
$data['content'] = $this->load->view('item', $data, true);
as
$db_data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
$data['content'] = $this->load->view('item', $db_data, true);
As it is, you are sending, as part of the JSON output, the query response from the DB (in the $data array). Then replace the last two lines with
echo json_encode($data);