我想从我的数据库'phpopdracht5'中检索数据,其中包含'用户'和属性'name'(VARCHAR(20))和'id'(INTEGER),但它只是不起作用。我的代码一定有问题
<?php
define("DB_HOST", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "phpopdracht5");
try
{
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname'.DB_NAME,DB_USERNAME,DB_PASSWORD);
}
catch(PDOException $e)
{
print "Error!:".$e->getMessage()."\n";
die();
}
$sth = $db_conn->prepare('SELECT * FROM users');
$sth->bindParam(':name', $name, PDO::PARAM_STR, 20);
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_BOTH)) {
echo $row[0];
}
?>
答案 0 :(得分:1)
绑定查询中不存在的参数。 您的查询必须是:
SELECT * FROM users WHERE name = :name AND id = :id
否则,如果您想要所有用户:
$sth = $db_conn->prepare('SELECT id, name FROM users');
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_BOTH)) {
echo $row['id'] . ':' . $row['name'];
}
答案 1 :(得分:1)
您无需绑定参数即可获取它们。只是
$sth = $db_conn->prepare('SELECT * FROM users');
$sth->execute();
此外,您必须按照此处的说明设置PHP和PDO错误报告:PDO query fails but I can't see any errors. How to get an error message from PDO?
答案 2 :(得分:0)
看起来你错过了一两个等号:
这是你的pdo命令: $ db_conn = new PDO('mysql:host ='。DB_HOST。'; dbname'.DB_NAME,DB_USERNAME,DB_PASSWORD);
这是一个不同的用户: $ db_conn = new PDO('mysql:host = localhost; dbname = testdatabase','test','testpass'); 链接:DEBUG PDO Connection & PHP Output
所以看起来“dbname =”缺失