从数据库中选择id=$id\u变量

xpcnnkqh  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(631)

我的数据库中有一个表叫做 posts 其中有一列 poster_id 链接到 idusers 通过外键创建表。
现在,我想从 users id等于 poster_id . 我正在使用pdo,我读了很多关于它的文章,但是我仍然无法修复我的bug。
我的代码从 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 等于海报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` table。
额外:此代码给我以下错误:

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

提前谢谢。
afdcj2ne

afdcj2ne1#

在这里:

$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}");

edit:好的,如果不起作用,请尝试一个带有绑定参数的准备语句,如下所示:

$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]);

相关问题