dongwu9170 2015-12-01 16:36
浏览 93
已采纳

使用pdo添加+1来更新行[关闭]

I am trying to add +1 to a row in my table and using the following code

 try {
$query = $con->prepare( "UPDATE sitename SET hits = hits + 1
             WHERE sitename = ?" );
$query->bindValue( 1, $url );
$query->execute();
// show error

} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

I think the table is set up right for the field hits, the type is int(11)

As you can see I am trying to learn as I go, also I have read a few questions on here that give a similar answers to the same problem but adapted the code to work.... in this case not to work.

in the above code I bind the value sitename, do I need to do the same for hits?

the following code does nothing to the row at all,

the following question on stackoverflow has a very detailed error and this is where i got the base of this code from, like I said I have done some searching around before posting I just think I'm missing something or completely not understanding the problem.

This code does not echo an error too.

  • 写回答

1条回答 默认 最新

  • dongqiongjiong4740 2015-12-01 17:02
    关注

    Two questions, two answers.

    First, as @Fred points out, remove the comma after hits = hits + 1 and the UPDATE statement will work.

    Second,

    in the above code I bind the value sitename, do I need to do the same for hits?

    No. You use bind variables to pass data between the SQL code and the client code (in this case, your php code.) Updating the value of hits is handled entirely within the SQL and is not passed in or out.

    With PDO you can also use named bind variables, which would look like this:

    $query = $con->prepare( "UPDATE sitename SET hits = hits + 1
                               WHERE sitename = :url" );
    

    and then either

    $query->bindParam(':url', $url);
    $query->execute();
    

    or simply

    $query->execute(array(':url' => $url));
    

    The above code has no error handling, as that was not the issue I was attempting to address. Error handling is important, but in this case I leave it as an exercise for the reader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数