PDO SELECT错误处理

时间:2016-02-10 10:00:56

标签: php mysql pdo

您好我正在尝试确保当用户登录网站时,他们是用户。使用MYSQL很容易,但我必须使用PDO,我正在努力弄清楚如何让它抛出错误信息而不是记录用户。

我在下面包含了PHP select语句..

$sql = "SELECT C.cid,C.first_name,C.sirname, S.sid 
         FROM CUSTOMER as C, 
              STAFF as S  
         WHERE C.email_address='".$email_address."' 
          AND C.password='".$password."' 
          AND S.CUSTOMER_CID=C.cid";

$runsql = static::db();
$runsql->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
//self::get()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    foreach ($runsql->query($sql) as $row) {
        /*if ($result = $runsql->prepare("SELECT C.cid,C.first_name,C.sirname, S.sid FROM CUSTOMER as C, STAFF as S  WHERE C.email_address='".$email_address."' AND C.password='".$password."' AND S.CUSTOMER_CID   =C.cid")) {
        */
        //print_r($runsql);
        //Check to make sure the user is on the staff list.
        $_SESSION['customer_id'] = $row->cid;
        $_SESSION['first_name'] = $row->first_name;
        $_SESSION['last_name']  = $row->sirname;
        $_SESSION['sid']  = $row->sid;
        $_SESSION['logged_in'] = true;
    }
} catch(PDOException $e) {
    /* If PDO fails we handle it here */
    echo "Your query failed: " . $e->getMessage();
}

1 个答案:

答案 0 :(得分:1)

首先,您必须了解如果找不到用户则不会出错。旧的mysql ext和PDO都没有。您需要检查的不是错误,而是您的查询是否返回任何内容。

为此,您只需拨打fetch()一次。

$sql = "SELECT C.cid,C.first_name,C.sirname, S.sid 
         FROM CUSTOMER as C, STAFF as S  
         WHERE C.email_address=? AND C.password=? 
         AND S.CUSTOMER_CID=C.cid";
$stmt = static::db()->prepare($sql);
$stmt->execute([$email_address,$password]);
$row = $stmt->fetch(PDO::FETCH_OBJ);

if ($row)
{
        $_SESSION['customer_id'] = $row->cid;
        $_SESSION['first_name'] = $row->first_name;
        $_SESSION['last_name']  = $row->sirname;
        $_SESSION['sid']  = $row->sid;
        $_SESSION['logged_in'] = true;
} else {
    echo "wrong credentials";
}

请注意,您必须在连接后立即设置ATTR_ERRMODE,并且永远不要更改它。

虽然真正的错误处理是一个与PDO无关的另一个问题,但对于整个站点必须是相同的。