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.

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置