@@ -6,26 +6,43 @@ class User {
66 private $ conn ;
77
88 public function __construct () {
9- $ this ->conn = (new Database ())->connect ();
9+ try {
10+ $ this ->conn = (new Database ())->connect ();
11+ } catch (Exception $ e ) {
12+ $ this ->conn = null ;
13+ error_log ("[ " . date ("Y-m-d H:i:s " ) . "] Connection failed: " . $ e ->getMessage (), 3 , '../../logs/error.log ' );
14+ }
1015 }
1116
12- public function getAllUser () : array {
13- if ( $ this -> conn ) {
17+ public function getAllUser () : ? array {
18+ try {
1419 $ query = "SELECT * FROM user " ;
20+
21+ if ($ this ->conn === null ) {
22+ throw new Exception ("Database connection is null. " );
23+ }
24+
1525 $ stmt = $ this ->conn ->query ($ query );
1626 return $ stmt ->fetchAll (PDO ::FETCH_ASSOC );
17- } else {
18- return [] ;
27+ } catch ( PDOException $ e ) {
28+ error_log ( " Query failed: " . $ e -> getMessage (), 3 , ' ../../logs/error.log ' ) ;
1929 }
2030 }
2131
22- public function getUserById ($ id ) : array {
23- if ($ this ->conn ) {
24- $ query = "SELECT * FROM user WHERE id= " . $ id ;
25- $ stmt = $ this ->conn ->query ($ query );
32+ public function getUserById ($ id ) : ?array {
33+ try {
34+ $ query = "SELECT * FROM user WHERE id=:id " ;
35+
36+ if ($ this ->conn === null ) {
37+ throw new Exception ("Database connection is null. " );
38+ }
39+
40+ $ stmt = $ this ->conn ->prepare ($ query );
41+ $ stmt ->bindParam (':id ' , $ id , PDO ::PARAM_INT );
42+ $ stmt ->execute ();
2643 return $ stmt ->fetchAll (PDO ::FETCH_ASSOC );
27- } else {
28- return [] ;
44+ } catch ( PDOException $ e ) {
45+ error_log ( " Query failed: " . $ e -> getMessage (), 3 , ' ../../logs/error.log ' ) ;
2946 }
3047 }
3148}
0 commit comments