php - PDO::setAttribute() doesn't seems to affect new PDO()? -
i have code
try { $dbh = new pdo('mysql:host=localhost;dbname=db_informations', 'root', ''); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception); } catch (pdoexception $e) { echo $e->getmessage(); }
and gives me exception message:
sqlstate[hy000] [1049] unknown database 'db_informations'
because correct name of database db_information
only.
my question is, if don't include line:
$dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception);
i still same exception , think it's not necessary use it? it?
this because that's behaviour of pdo::__construct()
can read in manual:
pdo::__construct() throws pdoexception if attempt connect requested database fails.
but if don't set error mode exception , do:
try { $dbh = new pdo('mysql:host=localhost;dbname=db_informations', 'root', ''); $dbh->query("select * atablewhichdoesnotexists"); } catch(pdoexception $e) { echo $e->getmessage(); }
you won't excpetion message or error, because didn't set error mode. need this:
try { $dbh = new pdo('mysql:host=localhost;dbname=db_informations', 'root', ''); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception); $dbh->query("select * atablewhichdoesnotexists"); } catch(pdoexception $e) { echo $e->getmessage(); }
to receive exception, can catch:
sqlstate[42s02]: base table or view not found: 1146 table 'test.atablewhichdoesnotexists' doesn't exist
also if think logically:
setattribute()
needs used ->
, means need instance of class call method. how able call method, if instance couldn't created correctly?
(so mean setattribute()
have bee static, can set something/call before take instance of class)
Comments
Post a Comment