简体   繁体   English

PHP更优雅的方式来处理mysqli错误

[英]PHP More elegant way to handle mysqli errors

With pure PHP code (and not frameworks) is there a more elegant way to handle mysqli errors as shown below: 使用纯PHP代码(而不是框架),有一种更优雅的方式来处理mysqli错误,如下所示:

if (!mysqli_query($con, $sql)) {
            # Throw error so we can handle them
            echo mysqli_error($con);

            # handle a duplicate email
            if (strpos(mysqli_error($con), "email_UNIQUE") !== false ) {
                    $_SESSION["errors_found"] = true;
                    array_push($_SESSION["error_messages"], "Email given is already registered.");
            }

            # handle a duplicate username
            else if (strpos(mysqli_error($con), "username_UNIQUE") !== false ) {
                    $_SESSION["errors_found"] = true;
                    array_push($_SESSION["error_messages"], "Username is already taken.");
            }

            # handle any other sql query error...
           else {
                die("Database query error: " . mysqli_error($con));
            }
    }

First of all, I wouldn't call such a process "handling mysqli errors", but rather "user input validation". 首先,我不会将这样的过程称为“处理mysqli错误”,而是“用户输入验证”。
And secondly, I wouldn't perform such a validation this way at all. 其次,我完全不会以这种方式执行这样的验证。

I've always been under impression that validating user input against database usually performed using SELECT queries, not INSERT ones. 我一直给人的印象是,根据数据库验证用户输入通常是使用SELECT查询而不是INSERT查询执行的。
It will not only make your application error-free, but also make it more flexible, allowing separate verifications for the AJAX-based registration for example. 它不仅使您的应用程序无差错,而且使它更加灵活,例如可以对基于AJAX的注册进行单独的验证。

As for the real mysqli errors - you really have to handle them, instead of just dying. 至于真正的mysqli错误-您真的必须处理它们,而不仅仅是死亡。
Most convenient yet easy way would be throwing an Exception: 最方便而又简便的方法是引发异常:

if (!mysqli_query($con, $sql)) {
    throw new Exception(mysqli_error($con));
}

which will be properly handled according to site-wide error handling settings and also provide priceless trace log. 它将根据站点范围的错误处理设置进行正确处理,并提供无价的跟踪日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM