douxueke5653 2018-07-04 04:00
浏览 151
已采纳

带有消息“无效数据源名称”的未捕获异常“PDOException”[重复]

I know there are many question regarding on stackoverflow but i read them all but my didn't fixed, so i asked new question. I have a file named as article.php and i have the this code init. Just a code which is showing error.

public static function getById( $id ) {
$conn = new PDO( DB_HOST, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM articles WHERE id = :id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $id, PDO::PARAM_INT );
$st->execute();
$row = $st->fetch();
$conn = null;
if ( $row ) return new Article( $row );

I am getting this error:

Fatal error: Uncaught exception 'PDOException' with message 'invalid data source name' in C:\wamp64\www\classes\Article.php on line 102
( ! ) PDOException: invalid data source name in C:\wamp64\www\cms\classes\Article.php on line 102

My config file looks like

ini_set( "display_errors", true );
define( "DB_HOST", "localhost" );
define( "DB_USERNAME", "username" );
define( "DB_PASSWORD", "" );
define('DB_NAME', 'name');

Can you tell me why this happens and where i am doing mistake. Thanks

</div>
  • 写回答

1条回答 默认 最新

  • dousha7645 2018-07-04 04:04
    关注

    Your current code seems to be used before with mysql or mysqli connector, however PDO is way more generic and supports multiple database vendors and not just MySQL. So you need to tell PDO which db to connect, etc.

    So PDO fails to make connection with only db name, your DB_HOST must be similar to this:

    define('DB_HOST','mysql:host=localhost;dbname=testdb');

    More options to connect:

    mysql:host=localhost;port=3307;dbname=testdb
    mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
    

    getting this error mysqli_real_escape_string() expects exactly 2 parameters, 1 given

    You don't need this since you are using PDO. Use PDO's API instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测