gpt4 book ai didi

php - 警告 : Invalid argument supplied for foreach() when retrieving data from database

转载 作者:行者123 更新时间:2023-11-29 14:26:20 25 4
gpt4 key购买 nike

我试图从两个表中检索数据并回显结果,sql 似乎是正确的,但它告诉我参数无效。这是我的代码:

// Retrieve all information related to this post
function get_post_data($post_id){

//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}

$sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id';
$result = $dbh->query( $sql );

foreach($result as $row):

echo $row['img_id'];

endforeach;

}

最佳答案

查询中的 $post_id 不会被扩展,因为该字符串是单引号的。

它应该可以更好地配合:

$sql = "SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id";

或者:

$sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = '.$post_id;

关于php - 警告 : Invalid argument supplied for foreach() when retrieving data from database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com