简体   繁体   中英

How to order the options by number of votes

I have just "created" a script that orders the songs by number of votes (see here : http://radiowhisper.com/demo/demo.php ), using a tutorial. And now, the problem: Everytime when i refresh the page i see the song names randomized. How can i order them by number of votes? ( FOR ALL THE TIME -> NOT TO BE RANDOMIZED ).

Info: The song names are writed in "sort-objects" table from PhpMyAdmin.

The tutorial: http://tutorialzine.com/2009/11/jquery-sort-vote/

Files:

demo.php

<?php

// Hiding notices:
error_reporting(E_ALL^E_NOTICE);

// Including file for the DB connection:
define("INCLUDE_CHECK",1);
require 'connect.php';

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Radio Whisper - Top 40</title>

<link rel="stylesheet" type="text/css" href="demo.css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

<script type="text/javascript" src="script.js"></script>

</head>

<body>

<div id="main">
    <h1>Radio Whisper - Top 40</h1>
    <h2>Ordonati melodiile in functie de preferinte.</h2>

    <hr />


<?php

// Checking whether the user has voted today:

$voted=false;

$vcheck=mysql_query("   SELECT 1 FROM sort_votes
                        WHERE ip='".$_SERVER['REMOTE_ADDR']."'
                        AND date_submit=CURDATE()");

if(mysql_num_rows($vcheck)==1)
    $voted=true;

// If we are not on the data.php?results page:
if(!array_key_exists('results',$_GET))
{
    echo '<ul class="sort">';

    // Showing the tutorials by random
    $res = mysql_query("SELECT * FROM sort_objects ORDER BY RAND()");

    while($row=mysql_fetch_assoc($res))
    {?>
        <li id="li<?php echo $row['id']?>">
        <div class="tut">
            <div class="tut-img">
                <img src="<?php echo $row['img']?>" width="50" height="50" alt="<?php echo $row['title']?>" />
                <div class="drag-label"></div>
            </div>

            <div class="tut-title">
                <a href="<?php echo $row['url']?>" target="_blank" title="Open it in a new window!"><?php echo $row['title']?></a>
            </div>

            <div class="tut-description"><?php echo $row['description']?></div>
            <div class="clear"></div>
        </div>
        </li>
    <?php } ?>

   </ul>

    <div class="button-holder">
        <?php if(!$voted):?><a href="" id="submitPoll" class="button">Trimite topul<span></span></a><?php endif;?>
        <a href="?results" class="button">Vezi rezultatele<span></span></a>
    </div>

<?php
}
else require "results.php";
// The above require saves us from having to style another separate page

?>


<!-- The form below is not directly available to the user -->

<form action="?results" id="sform" method="post">
<input name="sortdata" id="sortdata" type="hidden" value="" />
</form>

</body>
</html>

demo.css

body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{
    /* A simple page reset */
    margin:0px;
    padding:0px;
}

body{
    color:white;
    font-size:13px;
    background: url(img/bg.jpg) repeat-x #003951;
    font-family:Arial, Helvetica, sans-serif;

    text-shadow:2px 2px 5px #333333;
}

.tut-title{
    font-size:20px;
    font-weight:bold;
}

.tut-description{
    color:#DDDDDD;
    font-family:Arial,Helvetica,sans-serif;
    font-size:17px;
    padding-top:5px;
}

.tut-img{
    border:0px solid white;
    float:right;
    margin:0 110px 0 0;

    width:50px;
    height:50px;
    overflow:hidden;

    /* CSS3 Box Shadow */
    -moz-box-shadow:2px 2px 3px #333333;
    -webkit-box-shadow:2px 2px 3px #333333;
    box-shadow:2px 2px 3px #333333;
    cursor:n-resize;
    position:relative;
}

.drag-label{
    /* The DRAG label that scrolls into visibility on hover */
    background:url(img/label_small.png) no-repeat;
    width:71px;
    height:25px;
    position:relative;
    margin-left:25px;
}

a.button{
    /* The pretty buttons on the bottom are actually hyperlinks.. */
    color:#434343 !important;
    display:block;
    float:left;
    font-size:10px;
    font-weight:bold;
    height:23px;
    margin:10px;
    padding:12px 10px 0 12px;
    position:relative;
    text-shadow:none;
    text-transform:uppercase;

    /* This is the left part of the button background image */

    background:transparent url(img/button_gray_bg.png) no-repeat;
}

a.button:hover{
    text-decoration:none !important;
    background-position:bottom left;
}

a.button:active{
    /* Offsetting the text 1px to the bottom on mouse-click*/
    padding-top:13px;
    height:22px;
}

a.button span{
    /* This span holds the right part of the button backgound */
    background:transparent url(img/button_gray_bg.png) no-repeat right top;
    height:35px;
    position:absolute;
    right:-2px;
    top:0;
    width:10px;
    display:block;
}

a.button:hover span{
    background-position:bottom right;
}

.button-holder{
    padding-left:107px;
}

ul.sort{
    /* This UL gets converted to a sortable by jQuery */
    font-family:"Myriad Pro",Arial,Helvetica,sans-serif;
    font-size:20px;
}

ul.sort li{
    margin:25px 50px 25px 0;
    height:102px;
    list-style:none;
}

.chart{
    /* Styling the chart container */
    background:#002A3C;
    border:1px solid #005A7F;
    height:300px;
    width:550px;
}

.bar{
    /* Each bar in the chart is a div. Colors and width are assigned later */
    height:17px;
    margin:15px;
    overflow:hidden;
    padding:15px 10px 10px;
    text-shadow:none;
    white-space:nowrap;
}

.bar a, .bar a:visited{
    color:white;
    font-size:12px;
}

.tot-votes{
    float:right;
    font-size:10px;
    font-weight:bold;
    position:relative;
    right:50px;
    text-transform:uppercase;
    top:18px;
}

/* General styles for the demo page */

h1{
    /* The title of the page */
    color:white;
    font-family:"MyRiad Pro",Arial,Helvetica,sans-serif;
    font-size:38px;
    font-weight:normal;
}

h2{
    /* The subtitle */
    font-family:"MyRiad Pro","Arial Narrow",Arial,Helvetica,sans-serif;
    font-size:16px;
    font-weight:normal;
    letter-spacing:1px;
    padding-left:2px;
    text-transform:uppercase;
    white-space:nowrap;
    margin:10px 0 25px;
}

#orig{
    /* The link that is positioned above the title */
    font-family:"MyRiad Pro",Arial;
    font-size:10px;
    letter-spacing:1px;
    padding-bottom:15px;
    text-transform:uppercase;
}

hr{
    /* The horizontal ruler */
    background-color:#BBBBBB;
    border:medium none;
    color:#BBBBBB;
    height:1px;
    margin:30px auto;
    width:450px;
}

.clear{
    /* The clearfix hack */
    clear:both;
}

#main{
    /* The main container */
    width:600px;
    margin:30px auto;
}

a img{
    border:none;
}

a, a:visited {
    color:#00BBFF;
    text-decoration:none;
    outline:none;
}

a:hover{
    text-decoration:underline;
}

.tutorial-info{
    text-align:center;
    padding:10px;
}

connect.php

<?php

if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');


/* Database config */  (Edit: I don't want to see them)

$db_host        = '*********';
$db_user        = '***********';
$db_pass        = '******';
$db_database        = '***************';

/* End config */



$link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');

mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");

?>

results.php

<?php

if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');

// If the poll has been submitted:
if($_POST['sortdata'])
{
    // The data arrives as a comma-separated string,
    // so we extract each post ids:
    $data=explode(',',str_replace('li','',$_POST['sortdata']));

    // Getting the number of objects
    list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));

    if(count($data)!=$tot_objects) die("Wrong data!");

    foreach($data as $k=>$v)
    {
        // Building the sql query:
        $str[]='('.(int)$v.','.($tot_objects-$k).')';
    }

    $str = 'VALUES'.join(',',$str);

    // This will limit voting to once a day per IP:
    mysql_query("   INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
                    VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");

    //  If the user has not voted before today:
    if(mysql_affected_rows($link)==1)
    {
        mysql_query('   INSERT INTO `sort_objects` (id,votes) '.$str.'
                        ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
    }
}

//  Selecting the sample tutorials and ordering 
//  them by the votes each of them received:
$res = mysql_query("SELECT * FROM sort_objects ORDER BY votes DESC");

$maxVote=0;
$bars=array();

while($row=mysql_fetch_assoc($res))
{
    $bars[]=$row;

    // Storing the max vote, so we can scale the bars of the chart:
    if($row['votes']>$maxVote) $maxVote = $row['votes'];
}

$barstr='';

// The colors of the bars:
$colors=array('#ff9900','#66cc00','#3399cc','#dd0000','#800080');

foreach($bars as $k=>$v)
{
    // Buildling the bar string:
    $barstr.='
        <div class="bar" style="width:'.max((int)(($v['votes']/$maxVote)*450),100).'px;background:'.$colors[$k].'">
            <a href="'.$v['url'].'" title="'.$v['title'].'">'.$v['short'].'</a> 
        </div>';
}

// The total number of votes cast in the poll:
list($totVotes) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_votes"));

?>


<div class="chart">

<?php echo $barstr?>

</div>

<a href="demo.php" class="button">Go Back<span></span></a>

<div class="tot-votes"><?php echo $totVotes?> votes</div>

script.js

$(document).ready(function(){
// Executed once all the page elements are loaded

    // Convert the UL with all the tutorials into a sortable list:
    $("ul.sort").sortable({
        handle : '.tut-img',
        axis:'y',
        containment: 'document',
        opacity: 0.6
    });

    // The hover method takes a mouseover and a mouseout function:
    $(".tut").hover(

        function(){

            $(this).find('.drag-label').stop().animate({marginTop:'-25px'},'fast');
        },

        function(){

            $(this).find('.drag-label').stop().animate({marginTop:'0'},'fast');
        }
    );

    // Binding an action to the submitPoll button:

    $('#submitPoll').click(function(e){

        // We then turn the sortable into a comma-separated string
        // and assign it to the sortdata hidden form field:

        $('#sortdata').val($('ul.sort').sortable('toArray').join(','));

        // After this we submit the form:
        $('#sform').submit();

        // Preventing the default action triggered by clicking on the link
        e.preventDefault();
    });

});

So, what's the problem ?!?

Don't want to be rude but instead of just copying and pasting code, you would actually read the code and try to understand it you might see these 2 lines

// Showing the tutorials by random
    $res = mysql_query("SELECT * FROM sort_objects ORDER BY RAND()");

Seriously, one of them is a comment on what the next line of code does!

ORDER BY is the part of the query that tells it how to sort the results. ORDER BY RAND() will, not surprisingly, give you randomly sorted results. Instead, you should do ORDER BY votes or whatever the name of the column that contains votes is. ORDER BY votes asc will sort them in ascending order (fewest votes first) and ORDER BY votes desc will sort them in descending order (most votes first).

This assumes that you have votes stored in a single field in your table. If that's not the case (eg, if you have a table with one record per vote), you'll need to tell us about your database schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM