我正在尝试学习如何在我的PHP中使用预准备语句,以从MySQL数据库中获取数据。目前我没有打印任何东西。
我需要有一个while循环来遍历我在数据库中的行。这是对的吗?
我在这里是正确的方式,还是我错过了什么?我在代码中做了一些评论来描述我在做什么。
<?php
$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");
// Execute prepared statement
if ($stmt->execute()) {
$success = true;
}
// Make variables ready
$head = null;
$desc = null;
$plac = null;
// Bind result to variables
$stmt->bind_result($head, $desc, $plac);
while ($stmt->fetch()) {
// What should go here?
echo "Headline: ".$head."Description: ".$desc."Place: ".$place;
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
if($success) {
echo "Selected Succesfull";
} else {
echo "Failed: " . $stmt->error;
}
}
?>
答案 0 :(得分:0)
执行该代码时应该给出错误:
参数编号无效:没有绑定参数
您需要在使用占位符时绑定参数
$stmt->bind_param("sss", $headline, $description, $place); //missing from your code
其中&#34; sss&#34;在这种情况下,dataType是一个字符串,$headline, $description, $place
是您用占位符替换的变量
您的代码应为
<?php
$stmt = $mysqli->prepare("SELECT * FROM fantasies WHERE headline = ? AND description = ? AND place = ? ORDER BY reg_date DESC LIMIT 3");
//bind parameters
$stmt->bind_param("sss", $headline, $description, $place);
if ($stmt->execute()) {
$stmt->bind_result($head, $desc, $plac);
while ($stmt->fetch()) {
echo "Headline: " . $head . "desc: " . $desc . "Place: " . $plac;
}
$stmt->close();
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
?>