1

I'm a newbie to php pdo. Here i'm trying to fetch my database records from database using prepared statements. But it didn't fetch the records. I'm getting this following error

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected

why i'm getting this error? why it didn't fetch the records from database?

<?php
$user = "root";
$password = "password";

    try {
        $conn = new PDO('mysql:host=localhost;database=evouchers', $user, $password);
        $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e){
        echo 'DATABASE ERROR : ' . $e->getMessage();
    }

    $sql = "SELECT UserName FROM ebusers ORDER BY UserName";
    $db = $conn->query($sql);
    $db->setFetchMode(PDO::FETCH_ASSOC);

    while($row = $db->fetch())
    {
        print_r($row);
    }
?>

3 Answers 3

4

in your db connection string instead of database use dbname

  $conn = new PDO('mysql:host=localhost;database=evouchers', $user, $password);
  ---------------------------------------^



 $conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);

Docs link: http://php.net/manual/en/pdo.connections.php

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks.. its working.. why we should use dbname in that place?
Every database system is a little different. Mysql just happens to use dbname.
it is requirement for PDO to use dbname for specifying databasename, you can see in the doc link.
now i'm getting the result like this Array ( [UserName] => Administrator ) Array ( [UserName] => Mr.Dependable ). if i want to fetch the Administrator, Mr.Dependable value means what should i do?
do it like echo $row['UserName']; you will get the value. let me know if any issue.
2

I think it should be

$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);

Alternatively try just after you init PDO

$conn->exec('USE evouchers;');

Comments

2

use the following line for pdo connection

 $conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.