This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
(3个答案)
5年前关闭。
正在尝试运行mySQL PDO查询。不知道为什么我会犯致命错误。我查过其他的帖子,但他们的答案似乎不能解决我的问题。
脚本正在连接到数据库。用户名和密码是正确的,我已经在下面的脚本中删除了它们。
我的输出:
Connected to database
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'nobody'@'localhost' (using password: NO)' in /home/a/public_html/d/inc/header.php:34 Stack trace: #0 /home/a/public_html/d/inc/header.php(34): PDO->__construct('mysql:host=;dbn...', NULL, NULL) #1 /home/a/public_html/d/inc/header.php(43): testdb_connect() #2 /home/a/public_html/d/article.php(3): include('/home/a/p...') #3 {main} thrown in /home/a/public_html/d/inc/header.php on line 34

我的代码:
<?php

/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'removed';
/*** mysql password ***/
$password = 'removed';
try {
function testdb_connect (){
    $dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
return ($dbh);
}
echo 'Connected to database';
}
catch(PDOException $e) {
    echo $e->getMessage();
}
$dbh = testdb_connect ();

$id=$_GET[id];
echo 'dfsdfs '.$id;
var_dump($dbh);
$sql="SELECT * FROM 'radiologyArticles' WHERE 'id' = :id";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<section>
    <header>
        <h2><?php echo $row['articleTitle']; ?></h2>
        <h3>A generic two column layout</h3>
    </header>
    <p>
    <?php echo $row['articleBody']; ?>
    </p>
</section>
<?php
}
// close the PDO connection
$link = null;
?>

最佳答案

/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'removed';
/*** mysql password ***/
$password = 'removed';

function testdb_connect ($hostname, $username, $password){
    $dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
    return $dbh;
}

try {
    $dbh = testdb_connect ($hostname, $username, $password);
    echo 'Connected to database';
} catch(PDOException $e) {
    echo $e->getMessage();
}

关于php - 致命错误:消息未捕获的未捕获异常“PDOException”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23855518/

10-10 07:44