0

我刚刚使用教程“创建”了一个按票数排序歌曲的脚本(参见此处:http ://radiowhisper.com/demo/demo.php)。现在,问题是:每次我刷新页面时,我都会看到歌曲名称是随机的。我如何按票数排序?(一直 -> 不随机)。

信息:歌曲名称写在 PhpMyAdmin 的“排序对象”表中。

教程:http ://tutorialzine.com/2009/11/jquery-sort-vote/

文件:

演示.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>

演示.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;
}

连接.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");

?>

结果.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>

脚本.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();
    });

});

所以有什么问题 ?!?

4

2 回答 2

2

不想粗鲁,但不仅仅是复制和粘贴代码,您实际上会阅读代码并尝试理解它,您可能会看到这两行

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

说真的,其中一个是对下一行代码的评论!

于 2012-06-29T18:33:28.803 回答
1

ORDER BY是查询的一部分,告诉它如何对结果进行排序。ORDER BY RAND()毫不奇怪,会给你随机排序的结果。相反,您应该做ORDER BY votes或包含投票的列的名称是什么。ORDER BY votes asc将按升序对它们进行排序(票数最少的优先),ORDER BY votes desc并将按降序对它们进行排序(票数最多的优先)。

这假设您将投票存储在表的单个字段中。如果不是这种情况(例如,如果您有一张表,每次投票只有一条记录),您需要告诉我们您的数据库模式。

于 2012-06-29T18:41:33.837 回答