php - 从 PDOException $e 返回特定项目

标签 php mysql pdo laravel-5

我在 routes.php 中有一个 try catch,效果很好。

Route::get('{provider}/login', function ($provider) {
try
{
OAuth::login($provider, function ($user, $userDetails) 
{
    $user->email = $userDetails->email;
    $user->name = $userDetails->firstName . ' ' . $userDetails->lastName;
    $user->first_name = $userDetails->firstName;
    $user->last_name = $userDetails->lastName;
    $user->picture = $userDetails->imageUrl;
        $user->about = $userDetails->summary;
    $user->save();
    });

    return view('home');

} 
catch (ApplicationRejectedException $e) 
{
    // User rejected application
} 
catch (InvalidAuthorizationCodeException $e) 
{
    // Authorization was attempted with invalid
    // code,likely forgery attempt
}
catch(PDOException $err)
{
    return redirect()->guest('home');
}   
});

我想做的是从 PDOException $err 消息中提取特定项目。

如果我尝试登录,我知道会因 PDO 异常而失败,并且我“dd”了我得到的错误:

QueryException {#397 
#sql: "insert into `users` (`email`, `name`, `first_name`, `last_name`, `picture`, `about`, `facebook_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
#bindings: array:9 [?
0 => "mhluzi@email.com"
etc....

我如何才能获得电子邮件地址?

我已经尝试过

$err->binding[0] 

等没有运气。

这有可能吗?

最佳答案

如果返回以下内容:

catch(PDOException $err)
{
    $thisMessage=$err->getMessage();
    dd($thisMessage);
}

整个字符串可用:

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'mhluzi@email.com' for key 'users_email_unique' (SQL: insert into `users` 

等等

所以我所做的就是用“*”替换“'”

然后能够访问我需要的内容。

catch(PDOException $err)
{
    $thisMessage = str_replace("'", "*", $err->getMessage());
    if(preg_match_all('/\*(.*?)\*/',$thisMessage,$thisMatch)) 
    {
        dd($thisMatch[1][0]); //first occurrence which is what we want
    }
}

输出:

"mhluzi@email.com"

关于php - 从 PDOException $e 返回特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692094/

相关文章:

php - 拉维尔 5 : "class App\Commands\Command not found"

PHP session 处理

php - 将\n 另存为 <br> 从 textarea 到数据库

javascript - onkeyup 函数仅触发一次

php - 何时使用 PDO 准备查询。 mysql_real_escape 错误

php - 关闭浏览器后清除缓存 - symfony2

PHP SDK - 如何让 example.php 工作?

php - 将 PHP 和 Sql 与 Python 混合使用

php - 通过浏览器使用 PDO 将 MySQL 表中的数据存储为 CSV

php - MySql 和 PDO : How to send a null param with bindParam()