Jump to content

Error: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected


Recommended Posts

The Database connection class Db (Config.php)

	class Db extends PDO {
	    private $host = "localhost";
	    private $user = "root";
	    private $pass = "";
	    private $dbName = "Users";
	    private $charset = "utf8mb4";
	    public function __construct() {
	        $dsn = "mysql:host={$this->host};dbName={$this->dbName};charset={$this->charset}";
	        parent::__construct($dsn, $this->user, $this->pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
	    }
	}
	

When I try to do an insert in my Data class (Data.php) 

	try
	        {
	            $pdo = new Db();
	            if ($_SERVER["REQUEST_METHOD"] == "POST")
	            {
	                $email = filter_var($_POST["Email"],FILTER_VALIDATE_EMAIL);
	            }
	           
	            $sql = "Insert into Users (Email,Name) values(:Email,:Name)";
	            $stmt= $pdo->prepare($sql);
	            $stmt->execute(array(
	                ':Email' => $_POST["Email"],':Name' => $_POST["Name"]
	            ));
	            if($stmt)
	            {
	                return true;
	            }
	        }
	        catch (PDOException $e)
	        {
	            die('Error: '.$e->getMessage());
	        }
	

I get this error No Database selected.  

If I do an isset() on $pdo are creating the object variable it returns true, which would indicate a connection was successful.   What am I missing here?

 

 

@gizmola and I both gave you code that you have not implemented. You should spend some time going through this PDO tutorial. Making a PDO connection is one of the simplest things you would ever need to do.

https://phpdelusions.net/pdo

This is all that is required to make a PDO connection. Anything you do beyond this, you should know exactly WHY you are doing more.

$con = new PDO("mysql:host=localhost;dbname=test", 'root', ''); 

 

Edited by benanamen
  • Like 2
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.