dongqianzong4275 2019-04-02 14:47
浏览 88
已采纳

性能:使用try(语句)和catch(输出错误)而不是检查电子邮件是否已存在

Very often i need to prevent querys to get executed when a value like a email already exist.

Until now i searched for the value like that:

$checkemailexist = $X['db']->prepare("SELECT uid FROM userdata WHERE uid = :uid LIMIT 1");
$checkemailexist->execute(array(
':uid'=>$uid
));

if(empty($checkemailexist)){
   INSERT QUERY ..
}

...

The problem on a big database with many rows, a string search even on a varchar can take a lot of performance and time.

So i made the uid column unique and tried something like that:

try{    
    $insertuser = $X['dbh']->prepare("
    INSERT INTO user (uid) VALUES (:uid) 
    ");

    $insertuser->execute(array(
    ':uid'=> $mail
    ));

} catch (PDOException $e) {
        header("Location: ...");
        exit(); 
}


Its working fine, but could the performance even be worse ?

  • 写回答

1条回答 默认 最新

  • dongzhuo1498 2019-04-02 14:56
    关注

    After making uid column an [unique] index, you made all your queries faster. Both queries, either SELECT or INSERT will have to check the index, and it will take them both the same time to perform.

    Adding an index to the column used for search for is the real answer to your question. As to whether to use a select query or to catch an exception during insert is a matter of taste.

    However, your second example is rather wrong. You shouldn't handle every PDOException the same way but only a specific exception related to this very case, as it's shown in my PDO tutorial.

    The best way would be to keep the unique index but add a keyword IGNORE to the query and then check the number of affected rows

    $insertuser = $X['dbh']->prepare("INSERT IGNORE INTO user (uid) VALUES (:uid)");
    $insertuser->execute(['uid'=> $mail]));
    if (!$insertuser->numRows()) {
        header("Location: ...");
        exit(); 
    } 
    

    adding IGNORE would suppress the unique index error, and you will be able to check whether such a value already exists by simply checking the number of affected rows

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c