因此,我正在努力学习在查询中使用准备好的语句,就像使用旧的mysql方式一样,但我运气不太好。
这是我的代码
<?php
$stmt = $db->stmt_init();
if($stmt->prepare("SELECT l.listingID, l.title, l.description, l.dateListed
FROM tbl_listings AS l
LEFT JOIN tbl_listing_type AS lt ON lt.listingID = l.listingID
LEFT JOIN tbl_type AS t ON t.typeID = lt.typeID
WHERE lt.typeID =?"))
{
$stmt->bind_param("i",$type);
$type = 1;
$stmt->bind_result($id, $title, $description, $date);
while($stmt->fetch())
{
echo $id . ' - ' . $title . ' - ' . $description . ' - '.$date."<br />";
}
$stmt->close();
}
else
{
echo "error";
}
但它并没有打印出任何内容,我在phpmyadmin中用1而不是?它返回记录,所以我知道查询是正确的,但我不确定我是否正确使用了准备好的位?有人能告诉我哪里可能出错吗?
非常感谢
在绑定之前,需要将值分配给$type
:
$type = 1;
$stmt->bind_param("i",$type);
$stmt = $db->stmt_init();
if($stmt->prepare("SELECT l.listingID, l.title, l.description, l.dateListed
FROM tbl_listings AS l
LEFT JOIN tbl_listing_type AS lt ON lt.listingID = l.listingID
LEFT JOIN tbl_type AS t ON t.typeID = lt.typeID
WHERE lt.typeID =?"))
{
$type = 1;
$stmt->bind_param("i",$type);
$stmt->execute(); <-- Was missing this in my original code
$stmt->bind_result($id, $title, $description, $date);
while($stmt->fetch())
{
echo $id . ' - ' . $title . ' - ' . $description . ' - '. $date . "<br />";
}
$stmt->close();
}?>
使其工作:)缺少执行查询所需的一行代码。