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