duanluo5096 2016-07-19 00:15
浏览 26
已采纳

php pdo sql如果存在行则返回

In PHP PDO trying to use SELECT COUNT(*) SQL to see if primary key exists (so then can update rather than insert),

When I call the function sqlCall; fetchColumn() returns 0 or 1 depending on if it exists or not, however when it is returned it always returns false?

How do I get it to return if row exists or not?

Thanks for help!!

 function sqlCall($primary) {

            $sql = $handler->prepare("SELECT COUNT(*) FROM  WHERE ". strtolower($primary)."=:".$primary);

            $sSqlParams = array(':'.$primary => $primary);

            $sql->execute($sSqlParams);


            if($sql->fetchColumn()==1){
                return 1;

            } else {
                return 0;
            }
            break;
}




try {
                $rows = sqlCall($primary);

                if($rows=True){
                    //UPDATE SQL
                } else {
                    //INSERT SQL
                }
}
catch(PDOException $er) {

                    die();
}
  • 写回答

1条回答 默认 最新

  • dongliyan7318 2016-07-19 00:44
    关注

    You are going about this wrong way - there is MySQL construct which allows you to do this without any need for workarounds. If you would like to update record if exists and if not insert it than use: INSERT ... ON DUPLICATE KEY UPDATE

    It goes like this:

    INSERT INTO table (primary_key, field_to_update) VALUES(primary_key_value, value_to_update) ON DUPLICATE KEY UPDATE field_to_update = value_to_update
    

    Whenever your primar_key will be already in database the record will be updated and if primary_key does not exists than new record will be created.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度