I am having a problem converting a div to a php variable. This works great as a div but I need to implement this into my php script to show this if the user is viewing another uses page this will display.
//Check to see if you are tracking this member.
$sqlFollow = mysql_query("SELECT * FROM follow WHERE follower_id= " .$id. " and myMember = " .$viewerID . " LIMIT 1");
$numTrack = mysql_num_rows($sqlFollow);
if ($numTrack < 1) {
$divValue = "Track This Person";
$onclick = "trackMember";
}
else {
$divValue = "Don't Track Person";
$onclick = "donttrackMember";
};
$display_tracking_option = '<div class="track_btn_div" id="addremoveTrack"><span class="follow_b">'.$divValue.'</span></div>';
Saving this in PHP as a value I am having trouble with the " vs '.
$display_tracking_option = '<div class="track_btn_div" id="addremoveTrack"><span class="follow_b">"'.$divValue.'"</span></div>';
You are adding the stuff to a variable using php so you don't need to echo anything:
$display_tracking_option = '<div class="track_btn_div" id="addremoveTrack"><span class="follow_b">'.$divValue.'</span></div>';
Simply concatenate the string.
Alternatively you could use sprintf():
$theString = '<div class="track_btn_div" id="addremoveTrack"><span class="follow_b">%s</span></div>'
$display_tracking_option = sprintf($theString, $onclick, $id, $viewerID, $divValue);
Another thing: why do you have inline stuff?
You probably want this:
$display_tracking_option = '<div class="track_btn_div" id="addremoveTrack"><span class="follow_b">'.$divValue.'</span></div>';
Related
I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}
I've got the following code, and the stuff before the javascript echos and the stuff after the javascript includes, but the javascript won't echo :/
$currentPage = $_POST["current_page"];
$nextPage = 1 + $currentPage;
$count = $_POST["cum_count"];
$total = $_POST["cum_total"];
$progress = $_POST["cum_progress"];
echo $currentPage . $nextPage;
# number of questions less 1
$numQs[2]=6;
$numQs[3]=3;
$numQs[4]=5;
$numQs[5]=34;
$numQs[6]=17;
$numQs[7]=43;
$falses = array('false');
for ($i=0; $i < $numQs[$nextPage]; $i++) {
array_push($falses,', false');
}
# the js is how the survey keeps track of where it is
echo "<script type='text/javascript'>\n
var c_name = 'whbssurvey';\n
var c_value = '$nextPage';\n
document.cookie=c_name + '=' + c_value;\n
// set survey info\n
var count = $count;\n
var total = $total;\n
var progress = $progress;\n
var qArray = [$falses];\n
</script>";
include("$nextPage.php");
P.S. In case anyone is thinking cum_count is something dirty, it's short for cumulative.
Are you sure it's not echoing? It's being done BEFORE you do your include. If that include is a complete html page, the JS would be echoed BEFORE the opening <html> tag (which makes for an invalid page).
As well, for dumping out multiline text like that, you should either drop out of PHP mode so it's just plaintext that'll get echoed out automatically, or use a HEREDOC. Since you're inserting a couple PHP vars into that output, the HEREDOC would probably be preferable.
Try echoing without the <script> and </script> tags. It's possible that it is being printed but your browser isn't rendering it for some reason. If you get all the code spewed on the page, it worked.
try:
echo "<script type='text/javascript'>\n" .
"var c_name = 'whbssurvey';\n" .
"var c_value = '$nextPage';\n" .
"document.cookie=c_name + '=' + c_value;\n" .
"// set survey info\n" .
"var count = $count;\n" .
"var total = $total;\n" .
"var progress = $progress;\n" .
"var qArray = [$falses];\n" .
"</script>";
I am using the following code:
$result = mysql_query("SELECT * FROM table LEFT JOIN table2
ON table.field = table2.field WHERE ( table.field = '$pid' )
AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%'
OR table2.field2 LIKE '%$q%' )");
if (empty($what)) {
$countpls = "0";
} else {
$countpls = mysql_num_rows($result);
}
<?php
if ($countpls > 10) {
echo '<a id=pgnvg href="' . $_SERVER['PHP_SELF'] . '?pg=' . ($startrow + 20) . '&q=' . ($what) . '">Next</a>';
} else {
echo "";
}
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo '<a id=pgnvg2 href="' . $_SERVER['PHP_SELF'] . '?pg=' . $prev . '&q=' . ($what) . '">Previous</a>';
} else {
echo "";
}
?>
I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.
I tried adding the 'else' but its still not working.
Any ideas?
if($countpls > 0){
$pg = $_POST['pg']?$_POST['pg']:1;
//if it's not the first page...
if($pg>1){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
}
//if you have more registers to show...
if(($countpls-(($pg-1)*10))>10){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
}
}
In order to calculate your offset to use in queries, use this:
$offset = ($_POST['pg']-1)*10;
It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:
if($countpls - $startrow > 20)
{
echo '<a id=pgnvg href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&q='.($what).'">Next</a>';
}
I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.
http://www.phpfreaks.com/tutorial/basic-pagination
I have gallery.php that loads images with src path from a database.
I also have an external main.js that detects a click on a .thumbnail.
Everything works flawlessly until I load different images (another category of images, another set) via ajax. (the load() function of jquery) Everything shows just fine, but a problem with javascript appears.
After that, I can't retrieve the src attribute of my thumbnail. Here's what I mean.
BEFORE AJAX
Category 1 pictures/thumbnails
<a class="thumbnail"><img src="ressources/images/image1Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image2Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image3Small.jpg" /></a>';
And so on...
AFTER AJAX CALL
Category 2 pictures/thumbnails
<a class="thumbnail"><img src="ressources/images/image4Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image5Small.jpg" /></a>';
<a class="thumbnail"><img src="ressources/images/image6Small.jpg" /></a>';
As you can see, everything is like before. The a tag has the same class as the old est of pictures. But when I call the function containing :
var path = $(this).children().attr("src");
It now returns : undefined instead of ressources/images/imageXSmall.jpg
I tried checking if $(this) returned something else after, but no success.
I was wondering if when an external .php file was loaded via jquery.load(), the link between those newly created <a class="thumbnail"> tags and main.js were lost. Like if I had to reload main.js after the jquery.load() function. Or something like that...
Thank you!
EDIT Here's the code:
When clicking on a link to different
category
.linkSubCat being different categories
$(".linkSubCat").click(function(){loadImages($(this).attr("id"));});
then
function loadImages(pCategory) {
switch (pCategory) {
case "subCat00":
$(".pics").load('loadImages.php',{category:0});
break;
case "subCat01":
$(".pics").load('loadImages.php',{category:1});
break;
case "subCat02":
$(".pics").load('loadImages.php',{category:2});
break;
case "subCat03":
$(".pics").load('loadImages.php',{category:3});
break;
default:
$(".pics").load('loadImages.php',{category:0});
break;
}
}
loadImages.php
<?php
$connection = mysql_connect("localhost","root", "") or die("Error Connecting : " . mysql_error());
if (!mysql_select_db("taktak")) die('Error connecting to database : ' . mysql_error());
function createThumbPHP() {
if(isset($_POST['category'])) {
if($_POST['category'] == 0){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 1){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 1");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 2){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 2");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}elseif($_POST['category'] == 3){
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 3");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
}
return $thumbHtml;
}
else {
$errorMSG = "Error Loading Images";
return $errorMSG;
}
}
echo createThumbPHP();
?>
So everything does what it's supposed to do. Here'sthe problem. This javascript code in main.js :
$(".thumbnail").click(
function(){
$('#imageBig img').remove();
var path = $(this).children().attr("src");
var newPath = path.substring(0, path.length-9);
var newPath2 = newPath += ".jpg";
var imageLoad = new Image();
$(imageLoad).load(function () {
if (--imageLoad == 0) {
// ALL DONE!
}
// anything in this function will execute after the image loads
$('#loader').hide();
var newImg = $('<img />').attr('src',$(this).attr('src'));
$('#imageBig').append( $(newImg) ); // I assume this is the code you wanted to execute
})
.attr('src',newPath2);
}
)
It removes the img in #imageBig, but doesn't seem to get the path of $(this).children().attr("src"); This script worked perfectly before I loaded different thumbnails (even with the same setup (classes, order, ...))
Try using the jQuery "live" event binding, eg
instead of this
$(".thumbnail").click(
use this
$('.thumbnail').live('click',
When using the regular event binders (eg $.click()), the handler is only bound to those elements matched at the time of the call. When you load new elements via AJAX, these will not be bound.
From the jQuery manual
Attach a handler to the event for all elements which match the current selector, now and in the future.
I am trying to generate a specific link and accompanying html depednant on the existance of a file. The code I am using to do so:
if(file_exists('../images/'. $pk . '.jpg'))
{
$imageSrc = "../images/". $pk . ".jpg";
$imagehtml = htmlentities(json_encode("<img src=\"".$imageSrc."\" >"));
$screenshotLink = "<p>View Screenshot";
}
else {
$screenshotLink = '';
}
This results in the following, useless html:
View Screenshot
I don't understand this, because the above is essentialy the same code as:
$html = htmlentities(json_encode($ARTICLE_DESC));
$imagehtml = htmlentities(json_encode("<img src='".$imageSrc."' >"));
echo "<a href='#' onclick=\"makewindows(" . $imagehtml . "); return false;\">
<img src='".$imageSrc."' width='".$imageSize["width"]."' height='".$imageSize["height"]."'></a>
<p>Click for full description </p>";
which produces the following html which works fine:
<a href="#" onclick='makewindows("<img src=\"..\/images\/160329461329.jpg\" >"); return false;'>
<img src="../images/160329461329.jpg" width="199" height="300"></a>
I know it has something to do with quotes, but I am not sure what exactly.
Try this:
$imagehtml = htmlspecialchars(json_encode("<img src=\"".$imageSrc."\" >"), ENT_QUOTES);
$screenshotLink = "<p>View Screenshot";
$imagehtml = htmlspecialchars(json_encode('<img src="'.$imageSrc.'" >'), ENT_QUOTES);
$screenshotLink = '<p>View Screenshot';
Why not use ticks?
Lookup the ENT_NOQUOTES parameter in the php manual
And htmlspecialchars() != htmlentities() btw.