dongnaoben4456 2018-02-13 20:49
浏览 28
已采纳

有没有办法将1加到列值而不先通过查询检索值?

I'm checking to see if a value already exists in the DB, if it does I want to just update the last_date as well as up the count (visit_num) by 1. I'm not sure if there's a more efficient way to do that than by running a query to retrieve the current number and then doing ++. This is what I currently have (without retrieving the column).

function subscribe($visit_num, $email, $last_visit_date){

$sql = 'SELECT 1 from `visits` WHERE `email` = ? LIMIT 1';
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(1, $email, PDO::PARAM_INT);
        $stmt->execute();

        if($stmt->fetchColumn()){
            $totalVisits = /*Somehow retrieve the current count*/ + $visit_num;

            $query = "UPDATE `visits` SET
                        `visit_num`=:visit_num,
                        `last_visit_date`=:last_visit_date
                    WHERE
                        `email` = :email";

            // prepare query statement
            $stmt = $dbh->prepare($query);

            // bind values
            $stmt->bindParam(":visit_num", $totalVisits);
            $stmt->bindParam(":last_visit_date", $last_visit_date);
            $stmt->bindParam(":email", $email);
            $res = $stmt->execute();

            if($res){
                $arr = array('message' => 'Added');
                echo json_encode($arr);
            }else{
                $arr = array('message' => "Error");
                echo json_encode($arr);
            }
}

I can just do (previous to this) a "SELECT COUNT(*) FROM 'visits' WHERE 'email' = '$email'" and add it but I'm not sure whether that's the best approach or if there's something better.

  • 写回答

1条回答 默认 最新

  • duanhuayong6687 2018-02-13 21:00
    关注

    Do this in one statement:

    UPDATE `visits` SET
       `visit_num`=`visit_num` + 1,
       `last_visit_date`=CURDATE()
    WHERE
       `email` = :email";
    

    If you need to know the number of visits for display or downstream logic in your application, then run the separate select, but that's an unrelated use case. Obviously you can switch out what you need to here, like changing the CURDATE() to your incoming parameter for this function.

    In the event that this email doesn't exist in the table and you want to perform an INSERT where the UPDATE would fail, you can still do this in one SQL Statement using INSERT...ON DUPLICATE KEY UPDATE syntax

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

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上