PHP插入语句只插入1次

时间:2016-04-18 05:23:19

标签: php mysql

我使用php插入评论 table.ive,给出变量 $ email $ starcount $ bookid < / strong>现在修复的值只是为了测试文件。 $ res 查询会检查是否有一行包含该图书ID和电子邮件。如果不是 $ sql 查询插入它,然后 $ nex 查询循环执行 starcount book < / strong> column = $ book

如果我更改了文件顶部的电子邮件,它应该插入新的信息数据库并提取新的和现有的starcount,但它不会发布,它只返回已经存在的starcount。我不明白为什么它不工作....我使用数组返回我的文件。

<?php
mysql_connect("localhost","root","");
mysql_select_db("FunReads");

$email = "sd";
$starcount = "2";
$bookid = "5";

$res = mysql_query("SELECT * FROM Review WHERE book_id='$bookid' AND user_email='$email'");

if (mysql_num_rows($res) != 0) {

    $array[]= array("starcount" => "already entered");

} else {

    $sql = mysql_query("INSERT INTO Review(book_id,starcount,user_email) values('.$bookid.','.$starcount.','.$email')");

    $nex = mysql_query("SELECT * FROM Review WHERE book_id='$bookid'");

    while($row = mysql_fetch_array($nex)){

        $star = $row["starcount"];

        $array[] = array("starcount" => $star);

    }
}

echo json_encode($array); 
//echo "[{"name":"n1","city":"NY"},{"name":"n2","city":"Paris"}, ...]

&GT;

3 个答案:

答案 0 :(得分:0)

在我看来“Review”表中的“book_id”是主键,因为你试图多次添加它,系统显示错误重复键。检查错误&amp;发表它。还要检查插入查询是否有效。

答案 1 :(得分:0)

您不应手动传递主键值    试试这个它会帮助你

<?php
 mysql_connect("localhost","root","");
 mysql_select_db("FunReads");
 $starcount="2";
 $email = "vinodh@gmail.com";
  $res=mysql_query("SELECT * FROM Review  WHERE email   ='$email'");
  if(mysql_num_rows($res)!=0){
      $array[]= array("starcount" => "already entered");
  }else{
         $sql=mysql_query("INSERT INTO Review (starcount,email)    values('.$starcount.','.$email')");
$nex=mysql_query("SELECT * FROM Review  WHERE email='$email'");
    while($row=mysql_fetch_array($nex)){
            $star = $row["starcount"];
            $array[] = array("starcount" => $star);
    }
  }
  echo json_encode($array);
 ?>

答案 2 :(得分:0)

我刚刚更新了你的代码,它对我来说很好。

&#13;
&#13;
<?php
mysql_connect("localhost","user","");
mysql_select_db("xyz");

$email = "hari@gmail.com";
$starcount = "2";
$bookid = "5";

$sql = "SELECT * FROM review WHERE book_id='$bookid' AND user_email='$email'";
$res = mysql_query($sql);

if (mysql_num_rows($res) != 0) {

    $array[]= array("starcount" => "already entered");

} else {
	$sql = "INSERT INTO review(book_id,starcount,user_email) values('$bookid','$starcount','$email')";
    $sql = mysql_query($sql);

    $nex = mysql_query("SELECT * FROM review WHERE book_id='$bookid'");

    while($row = mysql_fetch_array($nex)){

        $star = $row["starcount"];

        $array[] = array("starcount" => $star);

    }
}

echo json_encode($array); 
&#13;
&#13;
&#13;

示例输出:

[{&#34;历史starcount&#34;:&#34; 2&#34;},{&#34;历史starcount&#34;:&#34; 3&#34;},{&#34;历史starcount& #34;:&#34; 1&#34;},{&#34;历史starcount&#34;:&#34; 2&#34;},{&#34;历史starcount&#34;:&#34; 1&# 34;}]

我更新了插入查询,请尝试更新并进行测试。