load(); // Set database credentials from environment variables $this->host = $_ENV['DB_HOST']; $this->user = $_ENV['DB_USER']; $this->password = $_ENV['DB_PASSWORD']; $this->dbname = $_ENV['DB_NAME']; // Set DSN (Data Source Name) $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname; $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); // Create a new PDO instance try { $this->dbh = new PDO($dsn, $this->user, $this->password, $options); //echo 'Connected'; } catch (PDOException $e) { $this->error = $e->getMessage(); echo $this->error; } } // Prepare statement with query public function query($sql) { $this->stmt = $this->dbh->prepare($sql); } // Bind values public function bind($param, $value, $type = null) { if (is_null($type)) { switch (true) { case is_int($value): $type = PDO::PARAM_INT; break; case is_bool($value): $type = PDO::PARAM_BOOL; break; case is_null($value): $type = PDO::PARAM_NULL; break; default: $type = PDO::PARAM_STR; } } $this->stmt->bindValue($param, $value, $type); } // Execute the prepared statement public function execute() { return $this->stmt->execute(); } // Get result set as array of objects public function resultSet() { $this->execute(); return $this->stmt->fetchAll(PDO::FETCH_OBJ); } // Get single record as object public function single() { $this->execute(); return $this->stmt->fetch(PDO::FETCH_OBJ); } // Get record row count public function rowCount() { return $this->stmt->rowCount(); } public function beginTransaction() { return $this->dbh->beginTransaction(); } public function commit() { return $this->dbh->commit(); } public function rollBack() { return $this->dbh->rollBack(); } public function endTransaction() { return $this->dbh->commit(); } public function cancelTransaction() { return $this->dbh->rollBack(); } public function getPdo() { return $this->dbh; } public function lastInsertId() { return $this->dbh->lastInsertId(); } public function getConn() { return $this->dbh; } } ?>