Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Db {
- // The class instance
- protected static $instance;
- // A connection to the db
- private $connection;
- // Function to create and return an instance of the Db class
- public static function getInstance(){
- if( !(self::$instance) ){
- self::$instance = new self();
- }
- return self::$instance;
- }
- // Private class constructor prevents this class being instantiated other than by the getInstance() call
- private function __construct(){
- // Let's connect to the database here
- $config = parse_ini_file('./config.ini');
- $this->connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
- // If connection was not successful, handle the error
- if($this->connection === false) {
- // Handle error - notify administrator, log to a file, show an error screen, etc.
- throw new Exception('Database connection failed');
- }
- }
- /**
- * Query the database
- *
- * @param $query The query string
- * @return mixed The result of the mysqli::query() function
- */
- public function query($query) {
- // Query the database
- $result = $this->connection->query($query);
- return $result;
- }
- /**
- * Fetch rows from the database (SELECT query)
- *
- * @param $query The query string
- * @return bool False on failure / array Database rows on success
- */
- public function select($query) {
- $rows = array();
- $result = $this->query($query);
- if($result === false) {
- return false;
- }
- while ($row = $result -> fetch_assoc()) {
- $rows[] = $row;
- }
- return $rows;
- }
- /**
- * Fetch the last error from the database
- *
- * @return string Database error message
- */
- public function error() {
- return $this->connection->error;
- }
- /**
- * Quote and escape value for use in a database query
- *
- * @param string $value The value to be quoted and escaped
- * @return string The quoted and escaped string
- */
- public function quote($value) {
- return "'" . $this->connection->real_escape_string($value) . "'";
- }
- // This prevents a bug in PHP to stop this class being cloned
- private function __clone() {}
- }
- try{
- // Our database object
- $db = Db::getInstance();
- // Quote and escape form submitted values
- $name = $db->quote($_POST['username']);
- $email = $db->quote($_POST['email']);
- // Insert the values into the database
- $result = $db->query("INSERT INTO `users` (`name`,`email`) VALUES (" . $name . "," . $email . ")");
- }
- catch (Exception $e){
- // Handle error - notify administrator, log to a file, show an error screen, etc.
- error_log($e->getMessage());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement