无法使用PHP脚本更新表

时间:2014-08-12 07:15:29

标签: php mysql

我写了一个php脚本来更新表。请参考以下代码:

<?php

/*
 * Following code will update view-status of seen queries
 * limit value is read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['limit'])) 
{

    $limit = $_POST['limit'];

    //echo "limit= " . $limit;
    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

    if (mysqli_connect_errno()) 
    {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    // mysql Updating view_status
    $result=mysqli_query($con,"UPDATE tbl_query_master t1 INNER JOIN (SELECT query_id FROM tbl_query_master WHERE view_status=0 ORDER BY query_date ASC LIMIT '".$limit."') as t2 on t1.query_id = t2.query_id SET t1.view_status=1");

    if($result)
    {
      // Record updated successfully
      $response["success"] = 1;
      $response["message"] = "Updated successfully.";
    }
   else
   {
        // Record updated successfully
      $response["success"] = 0;
      $response["message"] = "Oops! An error occurred.";
   }

     // echoing JSON response
     echo json_encode($response);
}
else 
{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

但由于某些未知原因,我上面的更新查询无法正常工作,并且给出了以下错误:

"{"success":0,"message":"Oops! An error occurred."}"

但是,如果我手动执行以下查询,那么它可以正常工作。

  UPDATE tbl_query_master t1 
  INNER JOIN (SELECT query_id 
  FROM tbl_query_master WHERE view_status=0 
  ORDER BY query_date ASC LIMIT 2) as t2 
  on t1.query_id = t2.query_id SET t1.view_status=1;

3 个答案:

答案 0 :(得分:1)

尝试更改字符串

$result=mysqli_query($con,"UPDATE tbl_query_master t1 INNER JOIN (SELECT query_id FROM tbl_query_master WHERE view_status=0 ORDER BY query_date ASC LIMIT '".$limit."') as t2 on t1.query_id = t2.query_id SET t1.view_status=1");

$result=mysqli_query($con,"UPDATE tbl_query_master t1 INNER JOIN (SELECT query_id FROM tbl_query_master WHERE view_status=0 ORDER BY query_date ASC LIMIT ".$limit.") as t2 on t1.query_id = t2.query_id SET t1.view_status=1");

$limit值附近不需要单引号。

答案 1 :(得分:0)

没有测试过它。但是希望它能帮助你好像是在改变

 $result=mysqli_query('your query',$con);

答案 2 :(得分:0)

使用bind_param

$stm=mysqli_prepare($con,"UPDATE tbl_query_master t1 INNER JOIN (SELECT query_id FROM tbl_query_master WHERE view_status=0 ORDER BY query_date ASC LIMIT ?) as t2 on t1.query_id = t2.query_id SET t1.view_status=1");
                                                                                                                                                         ^
$stmt->bind_param('d', $limit);

/* execute prepared statement */
$stmt->execute();

printf("%d Row updated.\n", $stmt->affected_rows);