Using a database class in my user class

前端 未结 6 614
慢半拍i
慢半拍i 2021-02-09 01:00

In my project I have a database class that I use to handle all the MySQL stuff. It connects to a database, runs queries, catches errors and closes the connection.

Now I

6条回答
  •  执笔经年
    2021-02-09 01:30

    Here is a solution using PDO.

    setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
                    self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
                    self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                } catch( PDOException $e ){
                    $error_message = $e->getMessage();
                    exit();
                }
                return self::$dbh;
            }
        }
    
        class MYObject {
            public static $dbh = null;
    
            public function __construct(PDO $db = null) {
                if($db === null){
                    $this->dbh = Database::connect();
                } else {
                    $this->dbh = $db;
                }
            }
        }
    
        class User extends myObject {
            public function __construct($id = null, PDO $db = null) {
                if($db === null){
                    parent::__construct();
                } else {
                    parent::__construct($db);
                }
    
                if($id !== null){
                    return $this->select($id);
                }
            }
    
            public function select($id) {
                $retVal =false;
                try {
                    $stmt = $this->dbh->prepare("SELECT...");
                    $stmt->execute();
    
                    if( $stmt->rowCount()==1 ){
                        $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        $retVal =json_encode($row);
                     }
                } catch (PDOException $e ) {
                    $error_message = $e->getMessage();
                    exit();
                }
                return $retVal;
            }
        }
    ?>
    

提交回复
热议问题