【问题标题】:How to update the database, if the user rate a product in ajax?如果用户在 ajax 中评价产品,如何更新数据库?
【发布时间】:2015-01-24 10:01:07
【问题描述】:

如果用户对其进行评分,我想更新数据库列“rate_score”和“rate_number”。 “rate_score”显示所有用户被评分的速率的总数。 “rate_number”显示对其评分的用户总数。如果用户没有对产品进行评分,他可以看到平均评分值。但是我的代码不起作用。

这是我的 PHP 代码。

$jsqla = mysql_query("select id,name,rate_score,rate_number,video_image from products where genre='$genre' limit 0,5");

if($jrowa['rate_number'] > 0){ 
  $ratea = $jrowa['rate_score'] / $jrowa['rate_number']; 
}else{ 
  $ratea = 0; 
}

这是我的 HTML 代码。

<input class="rating form-control input-star-rate" name="rating" value="<?php echo $ratea; ?>" data-min="0" data-max="5" data-step="0.3" data-size="xs" style="display: none; text-align: center;"/>

这是我的 jQuery 代码。

$(function(){
    $(document).ready(function(e) {
        var $stars = $('.input-star-rate');

        $stars.bind('change', function() {
          var $this = $(this); 
          var ratingValue = $this.val();
          var id = $this.attr("id");
          var num = parseInt("$this.attr("rate_number")")+1;

          $.ajax({
            type : "POST",
            url : "update_star_rate.php", 
            data : {product_id: id, rate_score: ratingValue, rate_number: num},
            success : function() {
                alert(ratingValue);
            }
          });
        });
    });
});

这里是“update_star_rate.php”的内容

<?php
    require_once("scripts/dcon.php");

    $rate_score=$_POST['rate_score'];
    $product_id=$_POST['id'];
    $rate_number=$_POST['rate_number'];

    $rate = "UPDATE products SET rate_score=$rate_score, rate_number=$rate_number WHERE id=$product_id" ;

    $result = mysql_query($rate) or die(mysql_error());
?>

【问题讨论】:

  • 您对alert(ratingValue) 的期望值是多少?您没有回显来自 update_star_rate.php... 的任何值
  • 并停止使用mysql_query。此扩展自 PHP 5.5.0 起已弃用,并将在未来删除。相反,应该使用 MySQLi 或 PDO_MySQL 扩展

标签: php jquery html ajax


【解决方案1】:
require_once("scripts/dcon.php");
if (isset($_POST['rate_score']) && !empty($_POST['rate_score'])){
    $rate_score=$_POST['rate_score'];
} //this will set only when data comes 
if (isset($_POST['rate_id']) && !empty($_POST['rate_id'])){
    $product_id=$_POST['id'];
} //this will set only when data comes 
if (isset($_POST['rate_number']) && !empty($_POST['rate_number'])){
   $rate_number=$_POST['rate_number'];
} //this will set only when data comes 

$rate = "UPDATE products SET rate_score=$rate_score, rate_number=$rate_number WHERE id=$product_id" ;

$result = mysql_query($rate) or die(mysql_error());

如果你的 ajax 数据正确,那么你将更新数据

【讨论】:

    【解决方案2】:

    使用这个

    data : 'product_id='+id+'&rate_score='+ratingValue+'&rate_number='+num,
    

    代替

    data : {product_id: id, rate_score: ratingValue, rate_number: num},
    

    在插入之前,检查所有变量是否正常工作。 (使用警报)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2022-08-19
      • 2016-08-21
      • 2020-10-29
      相关资源
      最近更新 更多