首页 > 解决方案 > 如何将单选按钮值传递给其他程序并使用 php 和 jquery 将值插入数据库

问题描述

我有一个带有多个单选按钮的表单。我想将单选按钮值存储在数据库中,例如 1 表示“是”,0 表示“否”。我正在使用相同的几个脚本 a.php、b.php,a.php 将获取单选按钮值并作为参数传递给 b.php。然后将 b.php 插入数据库。这里的问题是按钮值的数据库字段总是以 0 更新。我尝试使用 javascript 和其他一些 php 逻辑来实现。但没有运气。我还创建了其他小脚本来测试无线电值是否正常打印,工作正常。问题是我不知道如何在 b.php 的“推荐”中获得正确的值

我真的很感谢你的帮助。

a.php 如下所示:

<div id="result">
<label for="sel1">Would You recomend</label>
                    <div class="pull-left">

  <input name='recommend' type='radio' value=1>Yes

  <input name='recommend' type='radio' value=0>No 

<button class="btn btn-primary btn-sm" id="submit" type="submit" value="submit">submit</button>

b.php

<?php
require_once './config.php';

$pid = intval($_POST["pid"]);
$uid = intval($_POST["uid"]);
$score = intval($_POST["score"]);
$recommend = intval($_POST["recommend"]);

$aResponse['error'] = FALSE;
$aResponse['message'] = '';
$aResponse['updated_rating'] = '';

$return_message = "";
$success = FALSE;


$sql = "INSERT INTO `tbl_product_rating` (`product_id`, `user_id`, `ratings_score`, `recommend_score`) VALUES "
        . "( :pid, :uid, :score, :recommend)";
$stmt = $DB->prepare($sql);

try {

  $stmt->bindValue(":pid", $pid);
  $stmt->bindValue(":uid", $uid);
  $stmt->bindValue(":score", $score);
 $stmt->bindValue(":recommend", $recommend);

  //$stmt->execute(':pid' => $pid, ':uid' => $uid, ':score' => $score, ':recommend' => $recommend));
  $stmt->execute();
  $result = $stmt->rowCount();
  if ($result > 0) {
    $aResponse['message'] = "Your rating has been added successfully";
  } else {
    $aResponse['error'] = TRUE;
    $aResponse['message'] = "There was a problem updating your rating. Try again later";
  }
} catch (Exception $ex) {
  $aResponse['error'] = TRUE;
  $aResponse['message'] = $ex->getMessage();
}

if ($aResponse['error'] === FALSE) {
  // now fetch the latest ratings for the product.
  $sql = "SELECT count(*) as count, AVG(ratings_score) as score FROM `tbl_products_ratings` WHERE 1 AND product_id = :pid";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":pid", $pid);
    $stmt->execute();
    $products = $stmt->fetchAll();

    if ($products[0]["count"] > 0) {
      // update ratings
      $aResponse['updated_rating'] = "Average rating <strong>" . round($products[0]["score"], 2) . "</strong> based on <strong>" . $products[0]["count"] . "</strong> users";
    } else {
      $aResponse['updated_rating'] = '<strong>Ratings: </strong>No ratings for this product';
    }
  } catch (Exception $ex) {
    #echo $ex->getMessage();
 }
}

echo json_encode($aResponse);
?>

我在 a.php 中使用的 Jquery 将单选按钮值发送到 b.php:

<script>
$document.ready(function(){
 $('input[type="radio"]').click(function(){
 var recommend = $(this).val();
$.ajax({
 url:"b.php",
 method:"POST",
 data:{recommend:recommend},
// data:{recommend:$('#recommend').val($("[type='radio'] :checked").val())},
 success: function(data){
 $('#result').html(data);
 }
 });
 });
});
</script>

jquery 获取 pid,uid,score..

<script>
  $(document).on('click', '#submit', function() {
<?php
if (!isset($USER_ID)) {
  ?>
      alert("You need to have a account to rate?");
      return false;
<?php } else { ?>

      var score = $("#score").val();
      if (score.length > 0) {
        $("#rating_zone").html('processing...');
        $.post("update_ratings.php", {
          pid: "<?php echo $_GET["pid"]; ?>",
          uid: "<?php echo $USER_ID; ?>",
          score: score

        }, function(data) {
          if (!data.error) {
            // success message
            $("#avg_ratings").html(data.updated_rating);
            $("#rating_zone").html(data.message).show();
          } else {
            // failure message
            $("#rating_zone").html(data.message).show();
          }
        }, 'json'
                );
      } else {
        alert("select the ratings.");
      }

<?php } ?>
  });
</script>

我可以使用提到的 jquery 为单选按钮插入值 1,但它为 product_id..etc 等其他字段插入 0。我只想在 db 中插入一个条目,单选按钮的正确值以及其他字段.我已经提供了完整的插入(b.php)代码和ajax,它将值从a.php传递给b.php。请建议。

我想在mysql中输出如下:

ratings_id product_id user_id ratings_score recommend_score
1          17637       1      4              0

2          17638       2      2              1

现在情况如何:

ratings_id product_id user_id ratings_score recommend_score
    3           0         0       0              1

    6           17639     2      4              0

标签: javascriptphpjqueryhtmlmysql

解决方案


在用户单击单选按钮后触发的 ajax 中,您不会发送插入所需的其他值(pid、uid、score)。我想它们包含在半显示的表格中。

假设您的表单中有这些输入

<input name="pid" id="pid">
<input name="uid" id="uid">
<input name="score" id="score">

编辑:由于您现在显示了更多代码,因此我更新了下面的代码(以匹配您在正常表单提交中发送 pid 和 uid 的方式)。

您可以使用以下内容将它们添加到数据对象中:

data:{
   recommend:recommend,
   pid: "<?php echo $_GET["pid"]; ?>",
   uid: "<?php echo $USER_ID; ?>",
   score: $('#score').val(),
},

#newsletter也像其他人建议的那样改变双ID 。


推荐阅读