dsk49208 2018-02-07 19:09
浏览 104
已采纳

PHP / MYSQL - 在INSERT INTO的情况下检查成功/失败...不存在

I use the below query to add/insert a record only if an existing record with a certain value does not already exist:

php:

$query = "INSERT INTO accounts_mm (abc, name)
    SELECT '".$mysqli->real_escape_string($abc)."', '".$mysqli->real_escape_string($name)."' FROM DUAL  
    WHERE NOT EXISTS (
        SELECT abc FROM accounts_mm WHERE abc = '".$mysqli->real_escape_string($abc)."'
    )";

... it works ... but I always get 'Success' returned also in cases where no records were inserted.

if($mysqli->query($query)){
    echo json_encode(array('added' => 'Success!')); 
} else {
    echo json_encode(array('added' => 'Failure!'));     
}   

How can I check on success and failure for the above query?

Further attempts:

if(mysqli_affected_rows($mysqli->query($query)) > 0){
    echo json_encode(array('added' => 'Success!')); 
} else {
    echo json_encode(array('added' => 'Failure!'));     
}   
  • 写回答

1条回答 默认 最新

  • duandie0884 2018-02-07 19:20
    关注

    The query may succeed (not fail) but not insert because of WHERE NOT EXISTS. Just like a SELECT abc FROM accounts_mm WHERE abc = 1 will not generate an error but may not return results if there is no abc = 1. So you need to check the affected_rows:

    Use the object as you had been using it:

    $mysqli->query($query);
    
    if($mysqli->affected_rows() > 0){
        echo json_encode(array('added' => 'Success!')); 
    } else {
        echo json_encode(array('added' => 'Failure!'));     
    }   
    

    Or I guess you can combine them:

    if($mysqli->query($query) && ($mysqli->affected_rows() > 0)){
        echo json_encode(array('added' => 'Success!')); 
    } else {
        echo json_encode(array('added' => 'Failure!'));     
    }   
    

    Keep in mind, if $mysqli->query($query); returns false then the query didn't even execute due to an error, however if it returns true then the query executed but there may be no results.

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真