1+ <?php
2+ /**
3+ * PDO Database Class
4+ * Connect to database
5+ * Create prepared statements
6+ * Bind values
7+ * Return rows and results
8+ */
9+ class Database
10+ {
11+ private $ host = DB_HOST ;
12+ private $ user = DB_USER ;
13+ private $ pass = DB_PASS ;
14+ private $ name = DB_NAME ;
15+ 16+ private $ db_handler ;
17+ private $ stmt ;
18+ private $ error ;
19+ 20+ public function __construct ()
21+ {
22+ // Set DSN
23+ $ dsn = 'mysql:host= ' . $ this ->host . ';dbname= ' . $ this ->name ;
24+ $ options = [
25+ PDO ::ATTR_PERSISTENT => true ,
26+ PDO ::ATTR_ERRMODE => PDO ::ERRMODE_EXCEPTION ,
27+ ];
28+ 29+ // Create PDO Instance
30+ try
31+ {
32+ $ this ->db_handler = new PDO ($ dsn , $ this ->user , $ this ->pass , $ options );
33+ }
34+ catch (PDOException $ e )
35+ {
36+ $ this ->error = $ e ->getMessage ();
37+ echo $ this ->error ;
38+ }
39+ }
40+ 41+ // Prepare statement with query
42+ public function query ($ sql )
43+ {
44+ $ this ->stmt = $ this ->db_handler ->prepare ($ sql );
45+ }
46+ 47+ // Bind values
48+ public function bind ($ param , $ value , $ type = null )
49+ {
50+ if (is_null ($ type ))
51+ {
52+ switch (true )
53+ {
54+ case is_int ($ value ):
55+ $ type = PDO ::PARAM_INT ;
56+ break ;
57+ 58+ case is_bool ($ value ):
59+ $ type = PDO ::PARAM_BOOL ;
60+ break ;
61+ 62+ case is_null ($ value ):
63+ $ type = PDO ::PARAM_NULL ;
64+ break ;
65+ 66+ default :
67+ $ type = PDO ::PARAM_STR ;
68+ }
69+ }
70+ 71+ $ this ->stmt ->bindValue ($ param , $ value , $ type );
72+ }
73+ 74+ // Execute the prepared statement
75+ public function execute ()
76+ {
77+ return $ this ->stmt ->execute ();
78+ }
79+ 80+ // Get result set as array of objects
81+ public function resultSet ()
82+ {
83+ $ this ->execute ();
84+ return $ this ->stmt ->fetchAll (PDO ::FETCH_OBJ );
85+ }
86+ 87+ // Get single record as object
88+ public function single ()
89+ {
90+ $ this ->execute ();
91+ return $ this ->stmt ->fetch (PDO ::FETCH_OBJ );
92+ }
93+ 94+ // Get row count
95+ public function rowCount ()
96+ {
97+ return $ this ->stmt ->rowCount ();
98+ }
99+ }
0 commit comments