pdo mysql dsn,在数据库PDO中使用$ dsn字符串变量作为参数

在尝试从MySQL数据库中简单获取数组时,遇到了一个未捕获的异常,可能与PDO构造函数或驱动调用有关。为解决此问题,建议将代码放入try-catch块中,并打印出错误信息以进行调试。示例代码提供了如何使用try-catch处理可能出现的PDOException和其他Exception。
摘要由CSDN通过智能技术生成

Goal: to simply fetch array from a MySQL database.

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.

// Define Database Parameters

$dbhost = "localhost";

$dbname = "x";

$dbuser = "y";

$dbpass = "z";

// Invoke Driver (as a variable string)

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

// Connect to newly created db object

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

// Set the PDO error mode to enable exceptions

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

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

// Execute query to the database

$sql = "SELECT * FROM a_aif_remaining";

$sth = $dbh->prepare($sql);

$sth->execute();

// Present results from query

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;

// Close db connection

$dbh = NULL;

?>

解决方案

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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值