php order by 'most recent' 'most liked' 'least like' - php

I have a post system in place
<?php
/**
Display the results from the database
**/
$q = ("SELECT * FROM threads ORDER BY posted");
$r = mysql_query($q);
if(mysql_num_rows($r)>0): //table is non-empty
while($row = mysql_fetch_assoc($r)):
$net_vote = $row['votes_up'] - $row['votes_down']; //this is the net result of voting up and voting down
?>
<div class='entry'>
<span class='link'>
<?php echo $row['author']; ?>
<?php $row['posted'] = date("jS M Y h:i",$row['posted']); echo $row['posted']; ?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo $row['message']; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<br/>
<div class='message'><?php echo $row['message']; ?><br/></div>
<?php echo "<a href='msg.php?id=$row[id]'/> Comments/Add comments $row[replies]</a>" ?>
<?php echo "Likes: " . $row['votes_up'] . "&nbsp "; echo "Dislikes: " . $row['votes_down'] . "&nbsp"; ?>
</span>
<span class='votes_count' id='votes_count<?php echo $row['id']; ?>'></span>
<span class='vote_buttons' id='vote_buttons<?php echo $row['id']; ?>'>
<a href='javascript:;' class='vote_up' id='<?php echo $row['id']; ?>'></a>
<a href='javascript:;' class='vote_down' id='<?php echo $row['id']; ?>'></a>
<br/>
</span>
</div>
<br/>
<?php
endwhile;
endif;
?>
I want to add text that says 'order by : Most recent | Most liked | least liked '
As you can see i think ive got it already posting most recent by defualt which is what i want.
But what i want also is when you click 'Most liked' & 'least liked' it sorts by 'Vote_up' ( likes) & 'vote_down' (dislikes) all on the same page and shows posts with most likes on them (most liked) and most dislike (least liked)
EDIT***
sorry my question is how can i add 2 functions that when on click sorts by 'most liked' and 'least liked'

in html:
<a href='script.php?order=recent'>Recent</a>
<a href='script.php?order=liked'>Liked</a>
...
in php:
if ($_GET['order'] == 'recent') $order = "posted";
elseif ($_GET['order'] == 'liked') $order = "smth";
...
$q = "SELECT * FROM threads ORDER BY ".$order."";
but actually it's better to use some js framework (i prefer extjs for that) to sort the output on client side

AFAIK you have few choices how to do this:
Have the links pass a $_GET value via URL (causes a page refresh!!), then test for this in the PHP and run the necessary SQL to get the new record order.
Use AJAX to perform the same request asynchronously, with a PHP script to handle the SQL function and return the desired results.
Use a jQuery plugin such as tablesorter to (probably) basically provide the same functionality as that in 2, or via it's own filtering system -- I'm not sure i've not used it!!
My preference would be 1. (i.e a pure PHP + MySQL solution) as this offers the best universal functionality. You could always add javascript / ajax later to make things more swish for more modern browsers and users!

Related

Inserting PHP database into HTML table

Hey I've recently been making a website and want to display the data from my database in a grid format opposed to it just listing down the page.
Here is my code right now:
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
I was wondering how I would go about creating a for loop to allow the data from this database in conjunction with the image to span across the page with 7 columns and however many rows down until it reaches the end of the database.
Thanks!
<?php
$query = "Select * from tablename";
$bind = $conn->query($query);
if ($bind->num_rows > 0){
while ($row = $bind->fetch_assoc()){
?>
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
<?php
}
}
?>
Try this, I just add while loop until End Of file (EOF table)

simple php pagination or css pagination with php/mysql

I am trying to built a simple php pagination ( a sort of ).
or to be more specific css pagination with php/mysql.
Accessing and storing the values from db
while($row = $result->fetch_assoc()) {
$id[]=$row["id"];
$name[]=$row["name"];
$url[]=$row["url"];
//echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["url"]. "<br>";
}
Displaying them
<ul class="pagination">
<li>«</li>
<?php
$i=1;
for ($x = 0; $x < count($id); $x++) { ?>
<li>
<a href=<?php echo "$url[$x]"; ?> target="iframe1"
title="<?php echo "$name[$x]"; ?>"><?php echo "$i";?></a>
</li>
<?php $i++;} ?>
<li>»</li>
</ul>
Once any number shown above is clicked required url is displayed inside iframe1
<div align="center">
<iframe name="iframe1" src="http://www.w3schools.com"
frameborder='0' height='1000' width='1000' align="center"></iframe>
</div>
when I click any number it display the url inside the iframe "iframe1" .
Question:
How do i display first and NEXT {NOT LAST} record in
<li>«</li> [First]
<li>»</li> [Next]
I am looking for a very small code to do the same.
The first link is pretty easy:
<a href=<?php echo "$url[0]"; ?> target="iframe1"
title="<?php echo $name[0]"; ?>"><<</a>
For next link It would kind of depend on how your urls are set out. If the $url values are just a name and your url is domain.com/blog?page=page1 where page1 is the value from $url then we get use $_GET['page'] to grab the current page. Then using:
$next = array_search($_GET['page'], $url);
will give us the number in the order of the current page so the next page will simply be $url[$next + 1]
EDIT:
OK if its a url that changes in domain part then the $_GET wont work. You could grab the current url using $_SERVER[REQUEST_URI] and then use the same technique as above to find its position in the array of urls.

PHP Code is printing text not typed code

I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);

Advice on cleaner way to write this While statement

So the following code works, it is doing everything i want it to do. However, as i step back it seems like an overly convoluted approach to what is arguably one of the most common tasks in php.
I know enough about php to figure out what most things are doing when i see them, and to create some rather ugly code like you will see below; however, the finer points evade me.
I was hoping that if someone had some free time, he/she could look this over and show me a more concise way to approach this.
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<div id="item_gallery_s'.$i .'"'. 'class="fluid profileImgWrap goldDiagGrad">' .
'<div class="profile_name">' . $row['name'] . '<br /><span class="profile_date">' .
'<a href="http:#"
target="_blank"
title="some title">' . $row['place'] .
'</a></span></div><!-- DCD Diva Name -->' .
'<a rel="events[events]"
href="#">' .
'<div class="profile_banner">Custom Banner</div><!-- Banner -->' .
'<img src='.'"img/upload/'.$row['icon'].
'"' .
'alt="image description |'.$row['name'].
'"/>' .
'<!-- Photo --></a></div><!-- END #item_gallery_s'.$i .'-->';
$i++;
}?>
The loop itself is fine but you'll find varying opinions on the HTML-in-strings. For the past seven years I've encouraged my team to either use HTML with php tags or we rely on a full templating system:
<?php while ($row = mysql_fetch_assoc($result)): ?>
<div><?= $row['something'] ?></div>
<?php endwhile ?>
Though we have short tags enabled for even cleaner code. The benefit of this is that it's cleaner - less quotes, escaping problems, and IDEs will be able to syntax highlight the html. Most treat the html as string when it's inside quotes.
That's as "concise" as it gets.
You could not use an echo inside the while. And use php short tags.
while ($row = mysql_fetch_assoc($result)) {
?>
<?=$row['place'];?>
<?php
}
?>
Another way to "clean up", would be to use a template engine, but once again that would be just for the HTML part.
{place}
Good coding!
You can clean this up a bit by interspersing actual HTML, rather than simply echoing it:
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
?>
<div id="item_gallery_s<?php echo $i; ?>" class="fluid profileImgWrap goldDiagGrad">
<div class="profile_name">
<?php echo $row['name']; ?>
<br />
<span class="profile_date"><?php echo $row['place']; ?></span>
</div><!-- DCD Diva Name -->
<a rel="events[events]" href="#"><div class="profile_banner">Custom Banner</div><!-- Banner -->
<img src="img/upload/<?php echo $row['icon']; ?>" alt="image description |<?php echo $row['name']; ?>"/><!-- Photo --></a>
</div><!-- END #item_gallery_s<?php echo $i; ?> -->
<?php
$i++;
}?>
Another option, depending on how much work like this you have to do, would be a full-blown template engine such as Smarty.
Here's how I would probably format this code (as a matter of personal style):
<?php
$result = mysql_query('SELECT * FROM events');
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo
'<div id="item_gallery_s'.$i.'" class="fluid profileImgWrap goldDiagGrad">
<div class="profile_name">' . $row['name'] . '<br /><span class="profile_date">
<a href="http:#" target="_blank" title="some title">' . $row['place'] .
'</a></span>
</div><!-- DCD Diva Name -->
<a rel="events[events]" href="#">
<div class="profile_banner">Custom Banner</div><!-- Banner -->
<img src="img/upload/' . $row['icon']. '"
alt="image description |' . $row['name']. '"/>
<!-- Photo -->
</a>
</div><!-- END #item_gallery_s'.$i .'-->';
$i++;
}
?>
Try also to use consistent indentation to make it easy to tell what matches up with what. By the way, a <div> (block element) inside an <a> (inline element) is bad form. Did you mean to use a <span>? Learn to use the W3C validator to pick up this stuff.

Random banner display using php and mysql

I'm creating my website located here
I'm trying to add a banner that changes every time a page refreshes. I have set up 2 examples in my database called "link 1" and "link 2". I will want to add more as and when I get them.
What I want to happen is this:
I want to display one of the 2 images on my site and when the user refreshes the page, it will select one of the 2 images and this should continue every time the page refreshes.
I'm testing this out in a page called banner.php before I move it to my footer.php and make it live.
I currently have this code In my banner.php page:
<?PHP
include_once('include/connection.php');
// Edit this number to however many links you want displaying
$num_displayed = 1 ;
// Select random rows from the database
global $pdo;
$query = $pdo->prepare ("SELECT * FROM banners ORDER BY RAND() LIMIT $num_displayed");
$query->execute();
// For all the rows that you selected
while ($row = execute($result))
{
// Display them to the screen...
echo "<a href=\"" . $row["link"] . "\">
<img src=\"" . $row["image"] . "\" border=0 alt=\"" . $row["text"] . "\">
</a>" ;
}
?>
<br /><br /><br />
But I am getting this error code:
Fatal error: Call to undefined function execute() in banner.php on line 13
My connection page is used by other pages so I know it works.
Please can some one help me on what I am doing wrong.
Need any more info then please ask and I will add it to this post.
Thank you.
Kev
replace this
while ($row = execute($result))
with this:
while ($row = $query->fetch())
EDIT
This make it better to read.
while ($row = $query->fetch()) :
// Display them to the screen...
?>
<a href="<?php echo $row['link']; ?>">
<img src="<?php echo $row['image']; ?>" border="0" alt="<?php echo $row['text'];?>">
</a>
<?php endwhile; ?>
<br/>
<br/>
<br/>

Categories