error_reporting -1 function db static db if db null try db new PDO mys

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?
error_reporting(-1);
function db()
{
static $db;
if ($db === null) {
try {
$db = new PDO('mysql:host=127.0.0.1;db=test', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
return $db;
}
try {
db()->beginTransaction();
$x = db()->query("SELECT 1+1");
$y = db()->query("SELECT `2+2");
$u = db()->query("SELECT 3+3");
db()->commit();
} catch (PDOException $e) {
db()->rollBack();
echo $e->getMessage();
}