Jump to content

Recommended Posts

Hi I have been following a youtube tutorial trying to update my php knowledge and they use pdo to create the DB wrapper class and once i load my index.php through WAMP server i get the following on screen error:

Quote

SQLSTATE[HY000] [1049] Unknown database 'lr'

THIS IS THE DB CLASS FILE,

<?php
class DB {
    private static $_instance = null;
    private $_pdo, 
    $_query, 
    $_error = false, 
    $_results, 
    $_count = 0;
    
    private function __construct() {
        try {
            $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }
    
    public static function getInstance() {
        if(!isset(self::$_instance)) {
            self::$_instance = new DB();
        }
        return self::$_instance;
    }
    
    public function query($sql, $params = array()) {
        $this->_error = false;
        if($this->_query = $this->_pdo->prepare($sql)) {
            $x = 1;
            if(count($params)) {
                foreach($params as $param) {
                    $this-> _query->bindValue($x, $param);
                    $x++;
                }
            }
            
            if($this->_query->execute()) {
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->count = $this->_query->rowCount();
            } else {
                $this->_error = true;
            }
        }
        
        return $this;
    }
    
    public function action($action, $table, $where = array()) {
        if(count($where) === 3) {
            $operators = array('=', '>', '<', '>=', '<=');
            
            $field       = $where[0];
            $operator    = $where[1];
            $value       = $where[2];
            
            if(in_array($operator, $operators)) {
                $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?'";
                
                if(!$this->query($sql,array($value))->error()) {
                    return $this;
                }
            }
        }
        return false;
    }
    
    public function get($table, $where) {
        return $this->action('SELECT *', $table, $where);
    }
    
    public function delete($table, $where) {
        return $this->action('DELETE', $table, $where);
    }
    
    public function insert($table, $fields = array()) {
        if(count($fields)) {
            $keys = array_keys($fields);
            $values = '';
            $x = 1;
            
            foreach($field as $field) {
                $values .= '?';
                if($x < count($fields)) {
                    $values .= ', ';
                }
                $x++;
            }
            
            $sql = "INSERT INTO users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
            
            if(!$this->query($sql, $fields)->error()) {
                return true;
            }
        }
        return false;
    }
        
    public function results() {
        return $this->_results;
    }
    
    public function first() {
        return $this->results()[0];
    }    
    
    public function error() {
        return $this->_error;
    }
    
    public function count() {
        return $this->_count;
    }
    
}

 

THIS IS THE INIT.PHP FILE

 

<?php
session_start();

$GLOBALS['config'] = array (
    'mysql' => array(
        'host' => '127.0.0.1',
        'username' => 'root',
        'password' => '',
        'db' => 'lr'
    ),
    'remember' => array(
        'cookie_name' => 'hash',
        'cookie_expiry' => 604800
    ),
    'session' => array(
        'session_name' => 'user'
    )
);

spl_autoload_register(function ($class) {
    require_once 'classes/' . $class . '.php';
});

require_once 'functions/sanitize.php';

 

 

and this is the index.php file

 

<?php
require_once 'core/init.php';

$user = DB::getInstance()->query("SELECT username FROM users WHERE username = ?", array('alex'));

    if(!$user->count()) {
        echo 'No user';
    } else {
        echo 'OK';
    }

Edited by Michael_Baxter

The error is pretty obvious. There is no database named 'Ir' or the parameter Config::get (whatever that is) is not doing what you think. You can see what databases exist by opening a MySQL connection from the command line and entering 'show databases'.

i know that the database exists and i have tried this with 2 different databases

<?php
session_start();

$GLOBALS['config'] = array (
	'mysql' => array(
		'host' => '127.0.0.1',
		'username' => 'root',
		'password' => '',
		'db' => 'lr'
	),
	'remember' => array(
		'cookie_name' => 'hash',
		'cookie_expiry' => 604800
	),
	'session' => array(
		'session_name' => 'user'
	)
);

spl_autoload_register(function ($class) {
	require_once 'classes/' . $class . '.php';
});

require_once 'functions/sanitize.php';

this is where the config::get() refers to

Perhaps not so obvious. The error message indicates that the database it is trying to open is 'lr'. If the global was returning something different, it would not show up that way in the error message. That database must not exist at least in the way it is being referenced. Again a 'show databases' would verify that.

console.thumb.png.98f19345a514a312719c6b39d41348f5.png

ok so from the console i ran the show databases and there it is so i am still as thoroughly confused as to why i am getting this error and as i stated in the start i created all of this code and databases, tables and everything in line to a tutorial in which all this works just fine

most likely, either your actual database name contains some non-printing/white-space character(s) or the Config::get() method, which you haven't posted the code for, is adding some non-printing/white-space character(s) to the value (i'm betting either a new-line or a <br> tag.)

8 hours ago, Michael_Baxter said:

DB wrapper class

this code is just adding an unnecessary, pointless layer. it has no useful error handling, is using emulated prepared queries (the default), cannot be used with a LIMIT x term in a query, and can't be used with more than one connection or a different database type. if you want to do something useful for a database class, extend the PDO class and add a general prepared/non-prepared query method that will use a prepared query if there are input parameters and will use a non-prepared query if there are not. when you make the database connection, you should set the character set to match your database tables, set the error mode to exceptions, set emulated prepared queries to false, and set the default fetch mode to assoc (assoc works best when dynamically processing fetched data.)

Edited by mac_gyver
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.