致命错误:调用未定义的方法PDO :: error()

时间:2015-10-29 10:20:21

标签: php mysql pdo

显然这适用于我的老师,但对我来说它给出了错误致命错误:调用未定义的方法PDO :: error()

问题代码:

<!DOCTYPE html>
<html>
<head>
<title>Mini-Chat</title>
<meta charset="UTF-8">
<style>
form
{
text-align: center;
}
</style>
<body>

<form action="minichat-post.php" method ="post">
<p>
    <label for="username">Username</label> : <input type="text" name="username" id="username"/><br>
    <label for="message">Message</label> : <input type="text" name="message" id="message"/><br>
    <input type="submit" value="Send"/>
</p>
</form>
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$response = $bdd->query('SELECT username, message FROM minichat ORDER BY id DESC LIMIT 0, 10');
while ($data = $response->fetch())
{
echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
}
$response->closeCursor();
?>
</body>
</html>

更具体地说,它给出了错误行31,它是while循环:

while ($data = $response->fetch())
在这里疯了,因为它已经进行了一次小修正,但现在我似乎无法找到它的位置。

编辑:错误现在消失但它不会保存数据库中的任何消息,也不会在点击发送后显示它们。 这里的帖子php文件:

<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=minichat', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}

$req = $bdd->prepare('INSERT INTO minichat (username, message VALUES (?, ?)');
$req->execute(array($_POST['username'], $_POST['message']));
header('Location: ./mini-chat[conflit].php');
?>

2 个答案:

答案 0 :(得分:0)

添加此

fetch(PDO::FETCH_ASSOC);

在这里

fetch()

PDOStatement::fetch

答案 1 :(得分:0)

同时检查帖子

<?php
if(isset($_POST['username']) && isset($_POST['message'])) {
   try
   {
    $bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
    }
    catch(Exception $e)
    {
    die('Error :'.$e->getMessage());
    }
    $response = $bdd->query('SELECT username, message FROM minichat ORDER BY id DESC LIMIT 0, 10');
    while ($data = $response->fetch())
    {
    echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
    }
    $response->closeCursor();
}
?>