wiput1999
wiput1999

Reputation: 140

PDO Error I don't know how to fix

I have this error

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /srv/users/wiput/apps/gallery/public/auth.php:56 Stack trace: #0 /srv/users/wiput/apps/gallery/public/auth.php(56): PDOStatement->execute() #1 {main} thrown in /srv/users/wiput/apps/gallery/public/auth.php on line 56

in con.inc.php

<?
$db_server = "localhost";
$db_user = "gallery";
$db_password = "<censored>";
$db_name = "gallery";

$conn = new PDO("mysql:server=$db_server;Database=$db_name",$db_user,$db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

in auth.php

<?
ob_start();
session_start();

//Global Variable
$username = $_REQUEST["username"];
$password = $_REQUEST["password"];
//Convert to MD5
$md5_pw = md5($password);
//Check Blank form
if($username == '')
{
    $_SESSION["error"] = 2;
    header("location:index.php");
}
elseif($password == '')
{
    $_SESSION["error"] = 3;
    header("location:index.php");
}
else
{
    //Connect file
    require("con.inc.php");
    //Check data
    $sql = "SELECT * FROM member WHERE username= :username AND password= :md5_pw ";
    $result = $conn->prepare($sql);

    $result->bindValue(':username', $username);
    $result->bindValue(':md5_pw', $md5_pw);

    $result->execute();

    $data = $result->fetchAll( PDO::FETCH_ASSOC );

    if ($data !== false)
    {
        echo 'Hi! ', $data['firstname'];
    }
    else
    {
        $_SESSION["error"] = 1;
        header("location:index.php");
    }
}
?>

I use serverpilot web server with PHP 5.6. If any one can please fix it. Thank you :)

Upvotes: 1

Views: 397

Answers (2)

Albert Tai
Albert Tai

Reputation: 141

To add more to this, this is because your database could not selected. It could be various reasons. Try this: $conn = new PDO("mysql:host=$db_server;dbname=$db_name",$db_user,$db_password); rather than $conn = new PDO("mysql:server=$db_server;Database=$db_name",$db_user,$db_password); and see if it works as server is suppose to be host, and database is suppose to be dbname. I usually connect to the database by doing this $conn ->exec('USE gallery;');

Upvotes: 1

MatsLindh
MatsLindh

Reputation: 52822

As the error says, you don't have an active database selected. The reason is that your names in the DSN string is way off. In particular, Database should be dbname and server should be host (while the current value works because it defaults to localhost, probably - the dbname is what is giving you the error). Be sure to use the actual format and don't invent your own names.

See PDO_MYSQL DSN for the correct format.

Upvotes: 4

Related Questions