Re: [請益] try是否抓不到資料庫錯誤?
※ 引述《hirabbitt (兔子)》之銘言:
: 我想判斷一張資料表是否已存在
: 所以我寫了
: try{
: 建立資料表
: }catch(Exception $e){
: blalalala
: }
: 想說如果有"資料表已存在"的錯誤
: 我就可以blalalala了
: 但是好像一直都沒有出來耶
: 請問是為什麼呢
因為根本不會 throw exception 呀。
你應該先用 show tables like '$name' 來檢查;
根據回傳結果 return true 或是 throw new exceptions 。
比較麻煩的寫法
function check_table_exist($table_name)
{
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("show tables like '$name'", $link);
$num_rows = mysql_num_rows($result);
return ($num_rows > 0 ? TRUE : FALSE);
}
try
{
if(check_table_exist($table_name) == TRUE)
throw new Exception('Error Message');
else
// create table sql statement.
}
catch (Exception $e)
{
echo $e->getMessage();
}
比較簡單的寫法,以下用 PDO 改寫:
try
{
$dsn = "mysql:host=localhost;dbname=database";
$dbh = new PDO($dsn, "mysql_user", "mysql_password");
$sql = 'Create Table...'
$dbh->exec($sql) or throw new Exception('痾..');
// 這樣寫你的程式改動幅度比較小。
}
catch( PDOException $e )
{
echo $e->getMessage();
}
catch( Exception $e )
{
echo $e->getMessage();
// 這邊是你的 blalalala
}
--
任性是我僅有的溫柔..
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.220.104.63
推
07/06 19:37, , 1F
07/06 19:37, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
PHP 近期熱門文章
PTT數位生活區 即時熱門文章