我已经下载了本教程http://megarush.net/5-star-rating-system-with-php-mysql-jquery-and- ajax/,但出现以下错误:
注意:未定义的变量:第37行的C:\ xampp \ htdocs \ rating \ rating.php中的rat
注意:未定义变量:第41行的C:\ xampp \ htdocs \ rating \ rating.php中的v
<?php include("settings.php"); connect(); $ids=array(1,2,3); ?> <html> <head> <script src="jquery.js" type="text/javascript"></script> <link rel="stylesheet" href="rating.css" /> <script type="text/javascript" src="rating.js"></script> </head> <body> <?php for($i=0;$i<count($ids);$i++) { $rating_tableName = 'ratings'; $id=$ids[$i]; $q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id"; $r=mysql_query($q); if(!$r) echo mysql_error(); while($row=mysql_fetch_array($r)) { $v=$row['total_votes']; $tv=$row['total_value']; $rat=$tv/$v; } $j=$i+1; $id=$ids[$i]; echo'<div class="product"> Rate Item '.$j.' <div id="rating_'.$id.'" class="ratings">'; for($k=1;$k<6;$k++){ if($rat+0.5>$k)$class="star_".$k." ratings_stars ratings_vote"; else $class="star_".$k." ratings_stars ratings_blank"; echo '<div class="'.$class.'"></div>'; } echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.@number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast) </div> </div></div>';} ?> </body></html>
问题是由于这些变量的作用域。当您尝试在while循环之外回显那些变量时;PHP在循环内创建(和分配)变量时找不到它们。为了解决这个问题,也可以给两个外部变量都赋一个空白值:
if(!$r) echo mysql_error(); $rat = 0; $v = 1; // In case there are no records. while($row=mysql_fetch_array($r)) { $v = $row['total_votes']; $tv = $row['total_value']; $rat = $tv/$v; }