Php mysql用户评级和评论系统

I have the below given script for star rating. It is working fine but when i want to use $_GET variable in the processing file it is not taking it.

Also i want to use the comments with this script but i can not use $_POST or $_GET in tuto-star-rating.php.

I can get $_GET['sid'] in index.php but i can not get sid in tuto-start-rating.php. This tuto-start-rating.php is called through JS .

In index.php the url is index.php?sid=1

In tuto-star-rating.php i want to save the restaurant id using $_GET but unable to do that. I tried as below but it is not accepting it is only accepting the number putting directly as you can see in the file code below:

$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

I need help to integrate comment system with this code using a different form or by integrating in the same.

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  
?>

tuto-start-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;
}
?>

tuto-star-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>";
        }
    }
}
?>
dongnuochen9449
dongnuochen9449 如果你知道这个案子,请查看这个链接另一个问题。
接近 4 年之前 回复
dongsimu4422
dongsimu4422 请检查我回复我不能
接近 4 年之前 回复
dongsechuan0535
dongsechuan0535 我在下面给出了答案,希望这将解决您的问题。
接近 4 年之前 回复
dtnbjjq51949
dtnbjjq51949 我可以在index.php中获取sid,但我无法在tuto-start-rating.php中获取sid。这个tuto-start-rating.php是通过JS调用的
接近 4 年之前 回复
dongwuchu0314
dongwuchu0314 从你计划在index.php页面中获取sid值的地方?
接近 4 年之前 回复
drqwbh2150
drqwbh2150 在index.php中,我可以得到因为$_GET就在这里。但是在tuto-start-rating.php我可能无法在这里得到我将通过JS,但我无法在JS中配置。
接近 4 年之前 回复
drot98385
drot98385 如何在“tuto-star-rating.php”中获得$GET['sid']因为你的ajax是POST类型也“sid”不是来自ajax的数据
接近 4 年之前 回复

2个回答



来自你的评论,</ p>


我可以在index.php中获取sid但我无法在tuto-start-rating中获取sid .PHP。 这个tuto-start-rating.php是通过JS调用的</ p>
</ blockquote>

由于你将JavaScript作为外部文件包含,你不能使用/访问PHP变量,如< 您的 tuto-star-rating.js </ em>文件中的代码> $ _ GET ['sid'] </ code>。 您需要以下列方式更改 index.php </ em>和 tuto-star-rating.js </ em>文件,</ p>

index.php </ strong> </ p>

index.php </ em>页面中包含 tuto-star-rating.js </ em>文件之前, 添加以下行,</ p>

 &lt; script&gt; var sid =“&lt;?php echo $ _GET ['sid'];?&gt;”;&lt; / script&gt;

//包括你的tuto-star-rating.js文件
</ code> </ pre>

tuto-star-rating.js </ strong> </ p> \ n

您需要按以下方式更改AJAX请求,</ p>

  function rateMedia(mediaId,rate,numStar){

//您的代码

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

//你的代码
}) ;
}
</ code> </ pre>

通过这种方式,您可以访问 tuto-star-rating.php中的 sid </ em> </ em >使用 $ _ GET </ code>
superglobal的页面,如下所示:</ p>

  $ getRest = mysql_real_escape_string($ _ GET ['sid']); 
</ 代码> </ PRE>


<强> Sideno te:</ strong>不要使用 mysql _ * </ code>函数,从PHP 5.5开始不推荐使用它们,并且在PHP 7.0中完全删除它们。 使用 mysqli </ code> pdo </ code> 这就是为什么你不应该使用 mysql _ * </ 代码>功能。</ p>
</ div>

展开原文

原文

From your comment,

I can get sid in index.php but i can not get sid in tuto-start-rating.php. This tuto-start-rating.php is called through JS

Since you're including JavaScript as an external file, you cannot use/access a PHP variable like $_GET['sid'] in your tuto-star-rating.js file. Your need to change your index.php and tuto-star-rating.js files in the following way,

index.php

Just before you include tuto-star-rating.js file in index.php page, add this below line,

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

tuto-star-rating.js

You need to change your AJAX request in the following way,

function rateMedia(mediaId, rate, numStar) {

    // your code

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

        // your code
    });
}

In this way, you can access sid in tuto-star-rating.php page using $_GET superglobal, like this:

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

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

dtyqflrr775518
dtyqflrr775518 好,去吧。 :-)
接近 4 年之前 回复
duanbarong4617
duanbarong4617 我现在可以提出另一个问题吗?
接近 4 年之前 回复
dongzhang7382
dongzhang7382 如果您的其他问题需要使用代码修复进行正确解释,那么我建议您起草一个单独的问题并提出问题。
接近 4 年之前 回复
dtxooq1020
dtxooq1020 mysql_real_escape_string()不会阻止您的代码进行SQL注入。 正如我所建议的,开始使用mysqli或pdo,并始终准备,绑定和执行您的查询以防止任何类型的SQL注入。
接近 4 年之前 回复
dongwang6837
dongwang6837 是对不起它的工作没有mysql_real_escape_string我可以使用什么而不是这个安全? 如果有关于此脚本的其他内容,我可以在这里问你或者?
接近 4 年之前 回复
douxun7992
douxun7992 它对我来说很好。 你做了我上面建议的所有改变了吗? 在pastebin.com上粘贴完整的index.php和tuto-star-rating.js代码,并在此处给我链接。
接近 4 年之前 回复
dqs13465424392
dqs13465424392 我已经更新了我的答案。 现在它应该适合你。
接近 4 年之前 回复
dtja73027
dtja73027 那么请检查我的问题中的index.php它是如何得到的。 在index.php中,url是index.php?sid = 1或watever ........正如你所说我在我的js文件中改变的方式与你说的url相同:'comment / tuto-star-rating。 php?sid ='+ <?php echo $ _GET ['sid']; ?>,
接近 4 年之前 回复
dongtong7990
dongtong7990 以什么方式在index.php页面中获取此sid值? 另外,解释一下您在代码中所做的更改以及它是如何实现的。
接近 4 年之前 回复
dongyi9330
dongyi9330 我甚至不能通过这种方式尝试但失败
接近 4 年之前 回复



要解决$ _GET ['sid']首先要确保 sid </ em>传入url (例如:http://youdomainname.com/?sid = 1)</ em>。
然后,将 sid </ em>作为参数传递给 starBar </ em > </ strong>功能,如下所示:</ p>

  function starBar($ numStar,$ mediaId,$ starWidth,$ sid){
//你的代码在这里\ n}
</ code> </ pre>

调用函数时(在 index.php </ em>文件的最后),不要忘记传递新参数 :</ p>

  echo starBar(5,59,16,$ _GET ['sid']); 
</ code> </ pre>
</ div>

展开原文

原文

To solve the $_GET['sid'] first make sure the sid is passing in url (ex: http ://youdomainname.com/?sid=1). Then, pass the sid as a parameter to the starBar function as you can see bellow:

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

When you call the function (in the final of index.php file) don't forget to pass the new parameter:

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

dongtuan5367
dongtuan5367 它没有成功
接近 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐