我试图从两个表中检索数据并回显结果,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;
}
答案 0 :(得分:1)
查询中的$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;
答案 1 :(得分:0)
你需要告诉PDO抛出错误:
$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
这可能会告诉你发生了什么(除了在它之前创建pdo对象时的潜在问题......)。
我还建议切换到预准备语句,以避免潜在的SQL注入或格式错误的查询问题。
我希望这不是你真正的密码...