【问题标题】:how to use throw exception in mysql database connect [duplicate]如何在mysql数据库连接中使用抛出异常[重复]
【发布时间】:2012-04-07 20:45:42
【问题描述】:

我遇到了这个:-

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

并且明白抛出异常更好

如何在此代码中替换 die 并在此处使用 throw 异常:-

<?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"); 
?>

【问题讨论】:

  • 问自己同样的事情。感谢您发布这个问题:)

标签: php mysql error-handling database-connection


【解决方案1】:

这里记录了http://ie2.php.net/manual/en/mysqli.error.php

if (mysqli_connect_errno()) {
    throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error());
}

【讨论】:

  • 好的$db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database");我必须用这个$db = mysqli_connect($hostname_db, $username_db, $password_db); if (mysqli_connect_errno()) { throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error()); }替换
【解决方案2】:
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();
}

【讨论】:

  • 我需要用你的代码替换die("Unable to connect with Database");?另外你能告诉我@$_POST['variable']是什么@
  • 你应该用这个替换你的最后一行。 @ - 启用静默模式,不会回显错误,但仍会记录在服务器的 error.log 文件中。我想你知道$_POST['variable'] 是什么。
  • 是的,我知道...感谢您提供的信息 :)
  • 还有一件事,因为我已经在 include_db 文件中添加了用于数据库连接的代码......所以我应该把什么放在//do something 区域,因为它只需要连接或显示错误...
  • 您可以将其留空,如果没有错误,将继续执行 try...catch 块之后的代码。
猜你喜欢
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2016-09-25
  • 2020-07-15
  • 2019-08-19
  • 2014-09-18
相关资源
最近更新 更多