php pdo statement error

北慕城南 提交于 2020-01-06 13:10:03

问题


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);
    }
?>

回答1:


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




回答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;');



回答3:


use the following line for pdo connection

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


来源:https://stackoverflow.com/questions/20987336/php-pdo-statement-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!