我的数据库中有一个名为posts
的表,该表中有一个列poster_id
通过外键链接到id
表中的users
。
现在,我想从users
表中选择ID等于poster_id
的一些数据。我正在使用PDO,并且阅读了许多有关PDO的文章,但仍然无法修复存在的错误。
我从posts
中选择帖子的代码是:
$post_records = $conn->prepare('SELECT * FROM posts ORDER BY RAND()');
$post_records->execute();
$post_results = $post_records->fetchall();
$post_data = NULL;
$posts_count = $conn->query("SELECT count(*) FROM posts")->fetchColumn();
foreach ($post_results as $post_data) {
}
从users
中选择用户名的代码,其中id
等于poster_id:
$poster_id = $post_data['id'];
// Collect poster data from database
$poster_records = $conn->prepare('SELECT username FROM users WHERE id = {$poster_id}');
$poster_records->execute();
$poster_results = $post_records->fetchall();
$poster_data = NULL;
foreach ($poster_results as $poster_data) {
}
posts
表结构:http://prntscr.com/kh8gqz
users
表结构:https://prnt.sc/kh8h0f
外键链接到poster_id
表中的posts
和id
表中的users
之间。
其他:此代码给我以下错误:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''users' WHERE 'id' = '1'' at line 1 in F:\xampp\htdocs\home.php:57 Stack trace: #0 F:\xampp\htdocs\home.php(57): PDOStatement->execute() #1 {main} thrown in F:\xampp\htdocs\home.php on line 57
谢谢。
答案 0 :(得分:2)
在这里:
$poster_records = $conn->prepare('SELECT username FROM users WHERE id = {$poster_id}');
您在SQL语句中使用单引号,因此该字符串将按字面意义使用,这意味着变量$poster_id
不会扩展为其值。将该语句替换为双引号,然后重试:
$poster_records = $conn->prepare("SELECT username FROM users WHERE id = {$poster_id}");
编辑:好的,如果那不起作用,请尝试使用具有绑定参数的准备好的语句,如下所示:
$poster_records = $conn->prepare('SELECT username FROM users WHERE id = ?');
$poster_records->bind_param('i', $poster_id);
$poster_records->execute();
编辑2:使用PDO:
$poster_records = $conn->prepare('SELECT username FROM users WHERE id = :id');
$poster_records->execute([':id' => $poster_id]);