在数据库PDO中使用$ dsn字符串变量作为参数 [英] Using $dsn string variable as parameter in database PDO

查看:196
本文介绍了在数据库PDO中使用$ dsn字符串变量作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:仅从MySQL数据库中获取数组.

Goal: to simply fetch array from a MySQL database.

问题::我在PDO语句中使用$ dsn字符串变量"作为参数,但是似乎存在未捕获的异常,这与调用驱动程序或( PDO-> __ construct)-我不确定.您是否对如何修复$ dsn字符串变量或此代码的其他区域(可能导致其失败)有任何想法?预先感谢.

Issue: I am using the $dsn "string variable" as a parameter in the PDO Statement but there appears to be an uncaught exception and it has something to do with invoking the driver or the (PDO->__construct) -- I am not sure. Do you have any ideas on how to fix the $dsn string variable or other areas of this code that would cause it to fail? Thanks in advance.

//定义数据库参数

    $dbhost = "localhost";
    $dbname = "x";
    $dbuser = "y";
    $dbpass = "z";

//调用驱动程序(作为可变字符串)

    $dsn = "mysql:host=$dbhost;dbname=$dbname";

//连接到新创建的数据库对象

// Connect to newly created db object

    $dbh = new PDO($dsn, $dbuser, $dbpass);

//设置PDO错误模式以启用异常

// Set the PDO error mode to enable exceptions

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

//对数据库执行查询

    $sql = "SELECT * FROM a_aif_remaining";
    $sth = $dbh->prepare($sql);
    $sth->execute();

//显示查询结果

    print("PDO::FETCH_ASSOC: ");
    print("Return next row as an array indexed by column name");
    $result = $sth->fetch(PDO::FETCH_ASSOC);
    print_r($result);
    print("");
    return $results;

//关闭数据库连接

    $dbh = NULL;

    ?>

推荐答案

将代码放入try catch块中.并查看报告的错误消息.下面是一个示例:

Put your code in a try catch block. And see the error message reported. An example of this below:

try
{
  if ( !class_exists( 'PDO' ) )
    throw new Exception( 'PHP without PDO' );
  if ( array_search( PDO::getAvailableDrivers(), 'mysql' ) === false )
    throw new Exception( 'PHP without PDO mysql driver' );
  $dbh = new PDO( ... );
  ...
}
catch ( PDOException $e )
{
  print $e->getMessage();
}
catch ( Exception $e )
{
  print $e->getMessage();
}

这篇关于在数据库PDO中使用$ dsn字符串变量作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆