ERROR: "Invalid catalog name: 1046 No database selected in"

Hi everyone,

I have the error

  Fatal error : Uncaught PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected in /opt/lampp/htdocs/yonetimpaneli_phptr/class/VT.php:34 Stack trace: #0 /opt/lampp/htdocs/yonetimpaneli_phptr/class/VT.php(34): PDOStatement->execute(Array) #1 /opt/lampp/htdocs/yonetimpaneli_phptr/data/baglanti.php(5): VT->VeriGetir('ayarlar', 'WHERE ID=?', Array, 'ORDER BY ID ASC', 1) #2 /opt/lampp/htdocs/yonetimpaneli_phptr/index.php(13): include_once('/opt/lampp/htdo...') #3 {main} thrown in **/opt/lampp/htdocs/yonetimpaneli_phptr/class/VT.php** on line **34**".

Anyone help!!!

        <?php

class VT{

    var $sunucu="localhost";
    var $user="root";
    var $password="";
    var $dbname="yonetimpaneli_phptr";
    var $baglanti;

    function __construct()
    {   
        try{
        $this->baglanti=new PDO("mysql:host".$this->sunucu.";dbname=".$this->dbname.";charset=utf8",$this->user,$this->password);
        }catch(PDOException $e){

            echo $e->getMessage();
            exit();

        }
    }

    /* SELECT * FROM ayarlar WHERE ID=1 ORDER BY ID ASC LIMIT 1*/
    public function VeriGetir($tablo,$wherealanlar="",$wherearraydeger="",$orderby="ORDER BY ID ASC",$limit="")
    {
        $this->baglanti->query("SET CHARACTER SET utf8");
        $sql="SELECT * FROM ".$tablo; /*SELECT * FROM ayarlar*/
        if(!empty($wherealanlar) && !empty($wherearraydeger)){

            $sql.=" ".$wherealanlar; /*SELECT * FROM ayarlar*/
            if(!empty($orderby)){$sql.=" ".$orderby;}
            if(!empty($limit)){$sql.=" LIMIT ".$limit;}
            $calistir=$this->baglanti->prepare($sql);
            $sonuc=$calistir->execute($wherearraydeger);
            $veri=$calistir->fetchAll(PDO::FETCH_ASSOC);
        }else{
            if(!empty($orderby)){$sql.=" ".$orderby;}
            if(!empty($limit)){$sql.=" LIMIT ".$limit;}
            $veri=$calistir->fetchAll(PDO::FETCH_ASSOC);
        }
        if($veri!=false && !empty($veri)){

            $datalar= array();
            foreach($veri as $bilgiler){
                $datalar[]=$bilgiler; /*$sonuc[0]["baslik]*/
            }
            return $datalar;

        }else{
            return false;
        }
    }
}
?>

You are missing an equal sign = in the host part of the PDO connection string, so the rest of the connection string, containing the part that is specifying the database, wasn’t recognized. There are other problems in the code - it’s not executing the query without a where clause before trying to fetch the data and the foreach() loop is building an array exactly the same as the array the code is looping over.

This type of database wrapper class is useless. All it is doing is adding a lot of typing without adding any value to what you are doing. It only works for simple queries, doesn’t support using any aggerate functions, doesn’t recognize that there are WHERE clauses that don’t have any dynamic values, doesn’t support any GROUP BY or HAVING clauses, and doesn’t support using prepared query input parameters for the LIMIT clause.

Database abstraction layer classes, which provide a consistent programming interface for different database types, already exist. There’s no need to re-invent the wheel. If all you are doing is writing code that only works with one database type, you are just adding an unnecessarily layer that is exchanging one calling syntax for another, i.e. making more work for the person writing an sql query.

1 Like

It’s not clear where I missed equal sign in the PDO connection string, you mean this part:

function __construct()
{   
    try{
    $this->baglanti=new PDO("mysql:host".$this->sunucu.";dbname=".$this->dbname.";charset=utf8",$this->user,$this->password);
    }catch(PDOException $e){

        echo $e->getMessage();
        exit();

    }
}

Actually, I’m working with one database, but the only concise way I know this. What’s suggestion for solving the problem and coding the data?

Yes

Though like already explained by phdr the database wrapper class is useless.

I also don’t get why you are using arrays when PDO can handle the heavy lifting. It’s looks like you are doing a lot of unnecessary coding though that is just my opinion. Methods/Functions should be simple and serve a purpose for the rest of the coding.

An example is this pagination method that I wrote for my website:

/*
 * Pagination static function/method to limit
 * the number of records per page. This is
 * useful for tables that contain a lot of
 * records (data).
 */
public static function page($perPage, $offset, $loc = 'index'): array
{
    $sql = 'SELECT * FROM ' . static::$table . ' WHERE page=:page ORDER BY date_updated DESC LIMIT :perPage OFFSET :blogOffset';
    $stmt = Database::pdo()->prepare($sql); // Prepare the query:
    $stmt->execute(['perPage' => $perPage, 'blogOffset' => $offset, 'page' => $loc]); // Execute the query with the supplied data:
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

I have a separate class for my Database connection and just put use PDO and use PDOException; (If I use it) at the top of the class that I want use it for:

<?php

namespace Miniature;

use PDO;
class Database {

    private PDO $_connection;
    // Store the single instance.
    private static ?Database $_instance = null; // Don't initialize before it is called:

    // Get an instance of the Database.
    // @return Database:
    protected static function getInstance(): Database
    {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public static function pdo(): PDO
    {
        $db = static::getInstance();
        return $db->getConnection();
    }

    // Constructor - Build the PDO Connection:
    public function __construct() {
        $db_options = array(
            /* important! use actual prepared statements (default: emulate prepared statements) */
            PDO::ATTR_EMULATE_PREPARES => false
            /* throw exceptions on errors (default: stay silent) */
        , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            /* fetch associative arrays (default: mixed arrays)    */
        , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
        $this->_connection = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);
    }

    // Empty clone magic method to prevent duplication:
    private function __clone() {

    }

    // Get the PDO connection:
    protected function getConnection(): PDO
    {
        return $this->_connection;
    }

}
Sponsor our Newsletter | Privacy Policy | Terms of Service