2016-09-16 254 views
0

我有以下给定的星级评分脚本。它工作正常,但是当我想在处理文件中使用$ _GET变量时,它并没有采用它。Php mysql用户评分和评论系统

另外我想使用这个脚本的意见,但我不能在tuto-star-rating.php使用$ _POST或$ _GET。

我可以得到$_GET['sid']index.php但我不能在tuto-start-rating.php得到sid。这个tuto-start-rating.php是通过JS调用的。

在index.php文件的URL是index.php?sid=1

tuto-star-rating.php我想用$ _GET保存餐厅ID,但无法做到这一点。我尝试如下,但它不接受它仅接受将直接作为你可以在下面的文件代码中看到的数字:

$getRest = mysql_real_escape_string($_GET['sid']); 
$query = $bdd->execute('INSERT INTO rest_rating (sr_id, media, rate, ip, user) 
VALUES ('.$getRest.', '.$mediaId.', "'.$rate.'", "'.$ipaddress.'", "'.$user.'")'); // We insert the new rate 

我需要帮助使用不同的形式与此代码评论系统集成或整合在一起。

的index.php

<?php 
    include('comment/dbClass.php'); 
    $bdd = new db(); 
?> 
<style> 
    .no_star { display: inline-block; background: url("comment/star.png") no-repeat; width: 16px; height: 16px } 
    .star { display: inline-block; background: url("comment/star.png") no-repeat; background-position: 0 -16px; width: 16px; height: 16px } 
    .star_hover { display: inline-block; background: url("comment/star.png") no-repeat; background-position: 0 -32px; width: 16px; height: 16px } 
    .star_selected { display: inline-block; background: url("comment/star.png") no-repeat; background-position: 0 -48px; width: 16px; height: 16px } 
</style> 
<?php 
function starBar($numStar, $mediaId, $starWidth) { // function with arguments: number of stars, media ID, width of the star image 
    global $bdd; 

    $getRest = mysql_real_escape_string($_GET['sid']); 

    $cookie_name = 'tcRatingSystem'.$mediaId; // Set up the cookie name 

    // We get the rate average and number of rate from the database 
    $query = $bdd->getOne('SELECT round(avg(rate), 2) AS average, count(rate) AS nbrRate, sr_id AS sr_id FROM rest_rating WHERE media='.$mediaId.' and sr_id = "'.$getRest.'"'); 
    $avgCeil = round($query['average'], 0); // round above or below to show how many selected stars we display 

    $getJSON = array('numStar' => $numStar, 'mediaId' => $mediaId); // We create a JSON with the number of stars and the media ID 
    $getJSON = json_encode($getJSON); 

    // We create the DIV block with selected stars and unselected stars depending of the rate 
    $starBar = '<div id="'.$mediaId.'">'; 
    $starBar .= '<div class="'; 
    if(!isset($_COOKIE[$cookie_name])) $starBar .= 'star_bar'; 
    $starBar .= '" rel='.$getJSON.' style="width:'.($numStar*$starWidth).'px">'; 

    for ($i=1; $i<=$numStar; $i++) { 
$starBar .= '<div class="'; 
if ($i <= $avgCeil) $starBar .= 'star_selected'; else $starBar .= 'star'; 
$starBar .= '"></div>'; 
    } 
    $starBar .= '</div>'; 
    $starBar .= '<div class="resultMedia'.$mediaId.'" style="font-size: small; color: grey">'; // We show the rate score and number of rates 
    if ($query['nbrRate'] == 0) $starBar .= 'Not rated yet'; 
    else $starBar .= 'Rating: ' . $query['average'] . '/' . $numStar . ' (' . $query['nbrRate'] . ' votes)'; 
    $starBar .= '</div>'; 
    $starBar .= '<div class="box'.$mediaId.'"></div>'; // Return the text "Thank you for rating" when someone rate 
    $starBar .= '</div>'; 

    return $starBar; 
} 

echo starBar(5, 59, 16); // We create star bar 
?> 

政党成员 - 开始 - rating.php

<?php 
    session_start(); 
include('dbClass.php'); 
$bdd = new db(); 
    //$getRest = mysql_real_escape_string($_GET['sid']); 
    $ipaddress = $_SERVER["REMOTE_ADDR"]; 
    $user  = session_id(); 

if($_POST) {      

    $mediaId = $_POST['mediaId']; // Media ID 
    $rate = $_POST['rate']; // Your rate 

    $expire = 24*3600; // 1 day 
    setcookie('tcRatingSystem'.$mediaId, 'voted', time() + $expire, '/'); // Place a cookie 

    $query = $bdd->execute('INSERT INTO rest_rating (sr_id, media, rate, ip, user) 
     VALUES (1, '.$mediaId.', "'.$rate.'", "'.$ipaddress.'", "'.$user.'") 
     '); // We insert the new rate 

    // We calculate the new average and new number of rate 
    $result = $bdd->getOne('SELECT round(avg(rate), 2) AS average, count(rate) AS nbrRate FROM rest_rating WHERE media='.$mediaId.''); 

    $avgCeil = round($result['average'], 0); // Round the average 

    // Send JSON back with the new average, the number of rate and rounded average 
    $dataBack = array('avg' => $result['average'], 'nbrRate' => $result['nbrRate'], 'avgCeil' => $avgCeil); 
    $dataBack = json_encode($dataBack); 

    echo $dataBack; 
} 
?> 

政党成员星级rating.js

function rateMedia(mediaId, rate, numStar) { 
     $('.box' + mediaId).html('<img src="comment/loader-small.gif" alt="" />'); // Display a processing icon 
     var data = {mediaId: mediaId, rate: rate}; // Create JSON which will be send via Ajax 

     $.ajax({ // JQuery Ajax 
      type: 'POST', 
      url: 'comment/tuto-star-rating.php', // URL to the PHP file which will insert new value in the database 
      data: data, // We send the data string 
      dataType: 'json', 
      timeout: 3000, 
      success: function(data) { 
       $('.box' + mediaId).html('<div style="font-size: small; color: green">Thank you for rating</div>'); // Return "Thank you for rating" 
       // We update the rating score and number of rates 
       $('.resultMedia' + mediaId).html('<div style="font-size: small; color: grey">Rating: ' + data.avg + '/' + numStar + ' (' + data.nbrRate + ' votes)</div>'); 

       // We recalculate the star bar with new selected stars and unselected stars 
       var ratingBar = ''; 
       for (var i = 1; i <= numStar; i++) { 
        ratingBar += '<div class="'; 
        if (i <= data.avgCeil) ratingBar += 'star_selected'; else ratingBar += 'star'; 
        ratingBar += '"></div>'; 
       } 

       $('#' + mediaId + ' .star_bar').html(ratingBar).off('mouseenter'); 
      }, 
      error: function() { 
       $('#box').text('Problem'); 
      } 
     }); 
    } 

    $(function() { 
     $('.star_bar').on('mouseenter', function overBar(event) { // Mouse enter the star bar 
      var relData = $.parseJSON($(this).attr('rel')); // Get JSON values: number of stars and media ID 

      $(this).css('cursor','pointer'); 

      // We create a new star bar OVER the previous one with transparent stars 
      var newStarBar = ''; 
      for (var i = 1; i <= relData.numStar; i++) { 
       newStarBar += '<div class="no_star" id="' + i + '" title="' + i + '/' + relData.numStar + '" onclick="rateMedia(' + relData.mediaId + ', ' + i + ', ' + relData.numStar + '); return false;"></div>'; 
      } 
      $(this).css('position', 'relative').append('<div id="over' + relData.mediaId + '" style="position:absolute; top:0; left:0;">' + newStarBar + '</div>'); 

      // When we move the mouse over the new transparent star bar they become blue 
      $('#over' + relData.mediaId + ' > div').mouseover(function() { 
       var myRate = $(this).attr('id'); 
       for (var i = 1; i <= relData.numStar; i++) { 
        if (i <= myRate) $('#over' + relData.mediaId + ' #' + i).attr('class', 'star_hover'); 
        else $('#over' + relData.mediaId + ' #' + i).attr('class', 'no_star'); 
       } 
      }); 
     }); 

     // Mouse leaves the star bar, we remove the rating bar 
     $('.star_bar').on('mouseleave', function overBar(event) { 
      var relData = $.parseJSON($(this).attr('rel')); 
      $('#over' + relData.mediaId).remove(); 
     }); 
    }); 

**tuto-star-rating.php** 
<?php 
    session_start(); 
include('dbClass.php'); 
$bdd = new db(); 
    //$getRest = mysql_real_escape_string($_GET['sid']); 
    $ipaddress = $_SERVER["REMOTE_ADDR"]; 
    $user  = session_id(); 

if($_POST) {      

    $mediaId = $_POST['mediaId']; // Media ID 
    $rate = $_POST['rate']; // Your rate 

    $expire = 24*3600; // 1 day 
    setcookie('tcRatingSystem'.$mediaId, 'voted', time() + $expire, '/'); // Place a cookie 

    $query = $bdd->execute('INSERT INTO rest_rating (sr_id, media, rate, ip, user) 
     VALUES (1, '.$mediaId.', "'.$rate.'", "'.$ipaddress.'", "'.$user.'") 
     '); // We insert the new rate 

    // We calculate the new average and new number of rate 
    $result = $bdd->getOne('SELECT round(avg(rate), 2) AS average, count(rate) AS nbrRate FROM rest_rating WHERE media='.$mediaId.''); 

    $avgCeil = round($result['average'], 0); // Round the average 

    // Send JSON back with the new average, the number of rate and rounded average 
    $dataBack = array('avg' => $result['average'], 'nbrRate' => $result['nbrRate'], 'avgCeil' => $avgCeil); 
    $dataBack = json_encode($dataBack); 

    echo $dataBack; 
} 
?> 

dbClass.php

<?php 
class db { 
    private $conn; 
    private $host; 
    private $user; 
    private $password; 
    private $baseName; 
    private $port; 
    private $Debug; 

    function __construct($params=array()) { 
     $this->conn = false; 
     $this->host = 'localhost'; //hostname 
     $this->user = 'root'; //username 
     $this->password = ''; //password 
     $this->baseName = 'lepetit'; //name of your database 
     $this->port = '3306'; 
     $this->debug = true; 
     $this->connect(); 
    } 

    function __destruct() { 
     $this->disconnect(); 
    } 

    function connect() { 
     if (!$this->conn) { 
      $this->conn = mysql_connect($this->host, $this->user, $this->password); 
      mysql_select_db($this->baseName, $this->conn); 
      mysql_set_charset('utf8',$this->conn); 

      if (!$this->conn) { 
       $this->status_fatal = true; 
       echo 'Connection BDD failed'; 
       die(); 
      } 
      else { 
       $this->status_fatal = false; 
      } 
     } 

     return $this->conn; 
    } 

    function disconnect() { 
     if ($this->conn) { 
      @pg_close($this->conn); 
     } 
    } 

    function getOne($query) { // getOne function: when you need to select only 1 line in the database 
     $cnx = $this->conn; 
     if (!$cnx || $this->status_fatal) { 
      echo 'GetOne -> Connection BDD failed'; 
      die(); 
     } 

     $cur = @mysql_query($query, $cnx); 

     if ($cur == FALSE) {   
      $errorMessage = @pg_last_error($cnx); 
      $this->handleError($query, $errorMessage); 
     } 
     else { 
      $this->Error=FALSE; 
      $this->BadQuery=""; 
      $tmp = mysql_fetch_array($cur, MYSQL_ASSOC); 

      $return = $tmp; 
     } 

     @mysql_free_result($cur); 
     return $return; 
    } 

    function getAll($query) { // getAll function: when you need to select more than 1 line in the database 
     $cnx = $this->conn; 
     if (!$cnx || $this->status_fatal) { 
      echo 'GetAll -> Connection BDD failed'; 
      die(); 
     } 

     mysql_query("SET NAMES 'utf8'"); 
     $cur = mysql_query($query); 
     $return = array(); 

     while($data = mysql_fetch_assoc($cur)) { 
      array_push($return, $data); 
     } 

     return $return; 
    } 

    function execute($query,$use_slave=false) { // execute function: to use INSERT or UPDATE 
     $cnx = $this->conn; 
     if (!$cnx||$this->status_fatal) { 
      return null; 
     } 

     $cur = @mysql_query($query, $cnx); 

     if ($cur == FALSE) { 
      $ErrorMessage = @mysql_last_error($cnx); 
      $this->handleError($query, $ErrorMessage); 
     } 
     else { 
      $this->Error=FALSE; 
      $this->BadQuery=""; 
      $this->NumRows = mysql_affected_rows(); 
      return; 
     } 
     @mysql_free_result($cur); 
    } 

    function handleError($query, $str_erreur) { 
     $this->Error = TRUE; 
     $this->BadQuery = $query; 
     if ($this->Debug) { 
      echo "Query : ".$query."<br>"; 
      echo "Error : ".$str_erreur."<br>"; 
     } 
    } 
} 
?> 
+0

你是如何得到$ _GET [“SID”]在“政党成员 - 开始 - rating.php”作为Ajax是POST类型也是“SID”是不是在数据从阿贾克斯 – Farhan

+0

@Farhan以及在'index.php'我可以得到,因为$ _GET是直接在这里。但在'tuto-start-rating.php'我无法得到可能在这里我会通过JS,但我无法在JS中配置。 –

+0

从你打算在* index.php *页面获得* sid *值的地方? –

回答

1

your comment

我可以在index.php中获得sid,但是我无法在tuto-start-rating.php中获得sid。该政党成员 - 开始 - rating.php通过JS称为

既然你包括JavaScript作为外部文件,你不能用/你政党成员星级rating.js访问诸如$_GET['sid'] PHP变量文件。您需要更改index.phptuto-star-rating。JS文件按以下方式,

的index.php

你包括政党成员星级rating.js文件中的index.php页面只是之前,添加此线下方,

<script>var sid = "<?php echo $_GET['sid']; ?>";</script> 
// include your tuto-star-rating.js file 

政党成员星级rating.js

您需要更改以下列方式你的AJAX请求,

function rateMedia(mediaId, rate, numStar) { 

    // your code 

    $.ajax({ 
     type: 'POST', 
     url: 'comment/tuto-star-rating.php?sid=' + sid, 

     // your code 
    }); 
} 

通过这种方式,您可以使用$_GET 超全局中政党成员星级rating.php页面访问SID,像这样:

$getRest = mysql_real_escape_string($_GET['sid']); 

旁注:不要使用mysql_*功能,它们被弃用的PHP 5.5,并在PHP 7.0中完全删除。改为使用mysqlipdoAnd this is why you shouldn't use mysql_* functions

+0

我甚至不能通过这种方式我尝试,但失败 –

+0

@FahadAlmehaini你在* index.php *页面获得这个* sid *值的方式是什么?另外,解释你在代码中改变了什么,以及它是如何为你服务的。 –

+0

那么请检查index.php在我的问题,那里我如何得到。在index.php文件的URL是'的index.php SID = 1'或watever ........并为u说,我在我的JS文件相同的方式改变为u说'网址:“评论/政党成员星级-rating.php?sid ='+ <?php echo $ _GET ['sid']; ?>,' –

0

为了解决$ _GET [ 'SID']首先确保SID正在通过URL (例如:HTTP://youdomainname.com/ SID = 1)。 然后,通过SID作为参数传递给starBar功能,你可以看到波纹管:

function starBar($numStar, $mediaId, $starWidth, $sid) { 
    // your code here 
} 

当你调用该函数(在最后的index.php文件)唐“别忘了通过新的参数:

echo starBar(5, 59, 16, $_GET['sid']); 
+0

它没有运作 –