Recommended approach for error handling with PHP and MYSQL

Posted by iama on Stack Overflow See other posts from Stack Overflow or by iama
Published on 2010-05-21T18:57:49Z Indexed on 2010/05/21 19:00 UTC
Read the original article Hit count: 176

Filed under:
|
|

I am trying to capture database (MYSQL) errors in my PHP web application. Currently, I see that there are functions like mysqli_error(), mysqli_errno() for capturing the last occurred error. However, this still requires me to check for error occurrence using repeated if/else statements in my php code. You may check my code below to see what I mean. Is there a better approach to doing this? (or) Should I write my own code to raise exceptions and catch them in one single place? What is the recommended approach? Also, does PDO raise exceptions? Thanks.

function db_userexists($name, $pwd, &$dbErr)
{
    $bUserExists = false;
    $uid = 0;
    $dbErr = '';

    $db = new mysqli(SERVER, USER, PASSWORD, DB);

    if (!mysqli_connect_errno())
    {       
        $query = "select uid from user where uname = ? and pwd = ?";
        $stmt = $db->prepare($query);

        if ($stmt)
        {
            if ($stmt->bind_param("ss", $name, $pwd))
            {
                if ($stmt->bind_result($uid))
                {
                    if ($stmt->execute())
                    {
                        if ($stmt->fetch())
                        {
                            if ($uid)
                                $bUserExists = true;
                        }
                    }
                }
            }
            if (!$bUserExists)
                $dbErr = $db->error();

            $stmt->close();
        }       
        if (!$bUserExists)
            $dbErr = $db->error();      

        $db->close();
    }
    else
    {
        $dbErr = mysqli_connect_error();
    }

    return $bUserExists;
}

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql