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 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考