PHP, MySQL & JQuery Question? - php

I have this script that displays all the users images which i will display below.
My question: Is there a way I can display the first 10 images in the MySQL database and have the script hide the rest of the users images until the user clicks the link View All and have the rest of the images slide down when the user clicks the link?
Here is my PHP & MySQL script?
$multiple = FALSE;
$row_count = 0;
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['url'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';

Split the images into two parts. And set the second part to be hidden. Then add a click handler to slideDown. Here is the code:
UPDATE: it's not necessary to put the first 10 images into a div, but won't hurt either.
PHP
<?php
//echo '<div id="images">'; // visible images
while($row = mysqli_fetch_array($dbc)) {
// other stuff
// ...
// after the 10th image (0-9)
// open the hidden div
if ($i == 9) {
//echo '</div>'; // end of visible images
echo '<div id="hidden">'; // hidden images
}
}
echo '</div>'; // end of hidden
echo 'view all'; // view all
?>
jQuery
$(document).ready(function(){
$("#hidden").hide();
$("#view_all").click(function(){
$("#hidden").slideDown();
});
});
See it in action
Note: be sure not to hide the div with CSS. You do it in jQuery, and by this you allow users with JS disabled to get the content.

I'm not sure how many, or how large these images are, but if you want to make this scalable, I'd suggest doing an ajax callback that retrieves and fills in the "hidden" images, if the user requests them.

Yes, in your loop echoing out the list items, add the style="display:hidden" class="hidden" attribute when the count is > 10. Then use the window's scroll event to detect when the browser is scrolled near to the bottom of the window and then use jQuery to show the first hidden list item.
EDIT: This actually will show the items as the user scrolls down and does not need a "Show all button".
JQuery:
$(".hidden").hide();
$(window).scroll(function(){
if ($(window).scrollTop()+$(window).height > $("li:hidden:first").offset().top - SOMEPADDING )) {
$("li:hidden:first").fadeIn(200);
}
}

Related

How to call a function with database data inside another function?

EDITED: with new code after help from Sgt AJ.
Ok, so I am learning all the time, but since my coder stopped coding for our website, I am now having to learn PHP fully myself.
And I see all the time the coding where my coder made function calls inside other function calls.
So first of all the setup, we have a file for pretty much 95% of all functions in our site. That functions file basically has about 40-50 functions in it.
So I'm asking if someone can explain to me how is this possible to call a function inside another which works in the below instance, but when I try replicate it, it doesn't work? displays no data when I try to echo out the $user_info?
Like for example this function below: So Sgt AJ helped me solve the user avatar issue, so that will be removed from this question!
function showComments($v)
{
$mysqli = db_connect();
$v = mysqli_real_escape_string($mysqli,$v);
$sql = "SELECT * FROM `cl45-tbn_dir`.`comments` WHERE `v` = ? ORDER BY `id` ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$v);
$stmt->execute();
$result = $stmt->get_result();
while ($myrow = $result->fetch_assoc()) {
if ($myrow['post_approved']==1){
$user_info = getUserInfo($myrow['poster_id']);
if ($user_info['user_avatar_type']==1) {
$avatar = "https://www.tubenations.com/forum/download/file.php?avatar=".$user_info['user_avatar'];
} else {
$avatar = "https://www.tubenations.com/forum/styles/Flato%20-%20LightBlue%20-%20Main%20Style/theme/images/no_avatar.gif";
}
echo '<div class="comment">
<div class="avatar">
<a href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">
<img src="'.$avatar.'" />
</div>
<div class="name"><a class ="myaccount'.$user_info['group_id'].'" href="https://www.tubenations.com/users.php?id='.$myrow['poster_id'].'">'.$user_info['username'].'</a></div>
<div class="date" title="report this post">'.date("d M Y",$myrow['post_time']).'<form action="" class="flag" method="post"><button type="submit" value="'.$myrow['id'].'" name="vote" id="votebutton" alt="vote"><img src="/images/flag.png" alt="report this post!" /></button></form></div>
<p>'.stripslashesFull(clean($myrow['post_text'])).'</p>
</div>';
}
}
$stmt->close();
$mysqli->close();
}
As you can see, there is a line where it calls another function getUserInfo, $user_info = getUserInfo($myrow['poster_id']); that is another function inside this file, and that basically connects to our forum database and gets data.
But when I try to replicate this method by using this type of call within another, it doesn't work.
So basically what I was trying to play with was trying to make a function for displaying X users data with this below function
function getYouTubeInfo($page)
{
#$id = $_GET['id'];
print_r ($userdata['user_id']);
echo $myrow['user_id'];
echo $userdata['user_id'];
$db_link = mysqli_connect ('localhost', 'HIDDEN', 'HIDDEN', 'HIDDEN');
if ( !$db_link )
{
die('following error occured: '.mysqli_error());
}
$query = "SELECT user_id, yt_channelTitle, channel_id FROM points WHERE channel_id IS NOT NULL AND yt_channelTitle IS NOT NULL ORDER BY channel_id DESC;";
if($result = mysqli_query($db_link, $query)){
echo "";
$i = -1;
$objectsPerPage = 14;
$show_records = FALSE;
while ($row = $result->fetch_assoc())
{
if (!isset($_SESSION['last_slide'])) { $_SESSION['last_slide'] = $row['channel_id']; }
if ($row['channel_id'] == $_SESSION['last_slide']) { $show_records = TRUE; }
if ($show_records)
{
$i = $i+1;
if ($i > $objectsPerPage) { $_SESSION['last_slide'] = $row['channel_id']; echo 'BREAK: ', $row['channel_id']; break; }
$page = abs(floor($i/$objectsPerPage));
$youtube_info = $row;
$userdata = getUserInfo($row['user_id']);
if ($userdata['user_avatar_type']==1) {
$avatar = "/forum/download/file.php?avatar=".$userdata['user_avatar'];
} else {
$avatar = "/images/no_image.png";
}
if (($i/$objectsPerPage)==$page)
{
if ($page !=0) {
echo "</div></div>";
}
echo '<div class="cslide-slide">
<div class="slideTitles">Youtube Users Slide '.$page.'</div>
<div class="sections grouped">';
}
echo '
<div class="cols span_1_of_2">
<div class="memberTitles">'.$youtube_info['yt_channelTitle'].''.$i.';</div>
<div class="memberPicture"><img src="'.$avatar.'" title="Tube Nations Profile Picture" alt="Tube Nations Profile Picture"/></div>
<div class="memberTwitter"><div class="g-ytsubscribe" data-channelid="'.$youtube_info['channel_id'].'" data-layout="full" data-count="default" data-onytevent="onYtEvent"></div></div>
</div> ';
}
}
echo '</div></div>';
}
mysqli_free_result($result);
echo $_SESSION['last_slide'];
session_destroy();
mysqli_close($db_link);
}
So basically in the page in question, youtube.php, I just echo this getYouTubeInfo function.
This function I need to try get the users profile pictures that are in the forum database which is from the getUserInfo($id).
Also on a side note, I also can not work out how to re arrange the $i and $objectsPerPage variables and if statements so I can then use the $page inside the query LIMIT $page; because at the moment the page crashes with no limit, so I have had to put limit to 16 for now.
I use a jQuery slide script for displaying X per slide, so if I can just somehow work out how to make the query further down after the variables and if statements for the page stuff or get any help, I would appreciate it.
EDIT UPDATED REPLY: So now the problem is it now displays X per slide/page, but it now displays a gap after 8 results are displayed when it shows 10, but with a gap, and then on the the next slide button isn't showing up? so Sgt AJ said we need to somehow connect it to the jquery?, so I now will add a tag for jquery. (But can i say a big thanks to Sgt AJ for his help, really appreciate it) :)
Wow, you've got several things going on here.
First, your query right now says LIMIT 0;, which means you should get zero rows returned. Are you getting data back from this query??
Second, to get the page and items per page working right, you could go with something like this:
In your loop, keep your i=i+1 line
Add this if:
if ($i == $objectsPerPage)
{
++$page;
i = 1;
}
This will increment the page counter once the page is full, then reset the item count for the next page.
I just wanted to add more to my question, I think now the answer is with AJAX, so I think I need to somehow make the cslide jquery code recall the getYoutubeInfo($page) function
the jquery code for the cslide is this:
(function($) {
$.fn.cslide = function() {
this.each(function() {
var slidesContainerId = "#"+($(this).attr("id"));
var len = $(slidesContainerId+" .cslide-slide").size(); // get number of slides
var slidesContainerWidth = len*100+"%"; // get width of the slide container
var slideWidth = (100/len)+"%"; // get width of the slides
// set slide container width
$(slidesContainerId+" .cslide-slides-container").css({
width : slidesContainerWidth,
visibility : "visible"
});
// set slide width
$(".cslide-slide").css({
width : slideWidth
});
// add correct classes to first and last slide
$(slidesContainerId+" .cslide-slides-container .cslide-slide").last().addClass("cslide-last");
$(slidesContainerId+" .cslide-slides-container .cslide-slide").first().addClass("cslide-first cslide-active");
// initially disable the previous arrow cuz we start on the first slide
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
// if first slide is last slide, hide the prev-next navigation
if (!$(slidesContainerId+" .cslide-slide.cslide-active.cslide-first").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-prev-next").css({
display : "block"
});
}
// handle the next clicking functionality
$(slidesContainerId+" .cslide-next").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i+1;
var slideLeft = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").next(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideLeft
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) {
$(slidesContainerId+" .cslide-next").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) && $(".cslide-prev").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-prev").removeClass("cslide-disabled");
}
});
// handle the prev clicking functionality
$(slidesContainerId+" .cslide-prev").click(function(){
var i = $(slidesContainerId+" .cslide-slide.cslide-active").index();
var n = i-1;
var slideRight = "-"+n*100+"%";
if (!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-slide.cslide-active").removeClass("cslide-active").prev(".cslide-slide").addClass("cslide-active");
$(slidesContainerId+" .cslide-slides-container").animate({
marginLeft : slideRight
},250);
if ($(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-first")) {
$(slidesContainerId+" .cslide-prev").addClass("cslide-disabled");
}
}
if ((!$(slidesContainerId+" .cslide-slide.cslide-active").hasClass("cslide-last")) && $(".cslide-next").hasClass("cslide-disabled")) {
$(slidesContainerId+" .cslide-next").removeClass("cslide-disabled");
}
});
});
// return this for chainability
return this;
}
}(jQuery));
I also tweaked the code that Sgt AJ helped me with again, By adding a session_destroy() just before the closing brace. And also a few other bits, because I noticed that when you refreshed the page over and over, it just loaded the next 14 results, instead of the same first 14 results, so the actual code and logic seems to be working. so it is basically now down to we need to find a way to use AJAX and recall the function from the onclick event of the next/previous buttons.

How to Remember Checkbox/Radio-button Selection in a mulit-page form

We have a form that Span Across multiple pages and the form is full of checkboxes and radio-buttons. Requirement is that when a user navigates across multiple pages of the form, the user should be able to see the checkboxes and radio-buttons he has already Selected before the form Submit button is pressed.
I am copying the code segement that is used to generate the Checkboxes in the form - this is a Sample code Only.
<form action="car_model.php" method="post" name="car_form" id="car_form">
$q10 = "SELECT ...
$r10 = mysqli_query ($dbc, $q10);
if (mysqli_num_rows($r10) > 0) {
while ($row10 = mysqli_fetch_array($r10, MYSQLI_ASSOC))
{
echo '<p class="normal_text"><input type="checkbox" name="model_selection[]" value="' . $row10['model_id'] . '" onclick="return KeepCount()"; />' . $row10['car_model_name'] . '</p></br>';
}
}
</form>
if ($pages > 1) {
echo '<br /><p>';
// Determine what page the script is on:
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
echo '' . $i . ' ';
} else {
echo $i . ' ';
}
}
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}
echo '</p>';
}
I understand that JQuery is a Good tool for this purpose - how to use it?
If using server side session variables is not an option then you could implement it in such a way that when you click "next" instead of loading a new page you just hide the current content place holder of the visible part of the form and show the next one at it's place and the same when clicking back.
This can easily be done with jQuery. Here is a very simple example to get you started:
$("#next").click( function () {
$("#page1").hide();
$("#page2").show();
});
$("#back").click( function () {
$("#page1").show();
$("#page2").hide();
});
Fiddle
Good luck!

how to differentiate between these entries?

I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!

Can I show, hide and toggle results in PHP echo?

Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>​
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
​
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}

How to display all images when a link is clicked by using JQuery, PHP & MySQL?

I have this script that displays ten images or less by default but when a user clicks the <a> tag link it displays all the users images.
Is there a way I can display all the users images by having them slide down when a user clicks on the link <a> link instead of refreshing the page using JQuery or PHP?
Here is the php code.
if(isset($_GET['view']) && strlen($_GET['view']) == 1) {
$view = htmlentities(strip_tags($_GET['view']));
}
$multiple = FALSE;
$row_count = 0;
if(isset($view) == a) {
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
} else {
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'
LIMIT 0, 10");
}
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['avatar'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';
Have a look at jquery's load
http://api.jquery.com/load/
Update:
if you see in the examples provided you can use:
$('#result').load('ajax/test.html');
where you substitute #result with the id of the element (a <div> for example) where you want put your images
and the 'ajax/test.html' where you put the url of the php code that creates the image list

Categories