how to use throw exception in mysql database conne

2019-01-19 02:26发布

I come across this:-

PHP Error handling: die() Vs trigger_error() Vs throw Exception

and understood that throw exception is better

How can i replace die and use throw exception here in this code:-

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_db = "localhost";
$database_db = "database";
$username_db = "root";
$password_db = "password";
$db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database"); 
?>

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-19 02:55
try
{
    if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
    {
        //do something
    }
    else
    {
        throw new Exception('Unable to connect');
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}
查看更多
ら.Afraid
3楼-- · 2019-01-19 02:55

It is documented here http://ie2.php.net/manual/en/mysqli.error.php

if (mysqli_connect_errno()) {
    throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error());
}
查看更多
登录 后发表回答