的index.php
<a href="index.php?type=potato"><div>click here to select only potato</div></a>
$typesql = $_GET['type'];
$results = $mysqli->prepare("SELECT name, type FROM artists WHERE type = ?");
$results->bind_param("s", $typesql);
$results->execute();
$results->bind_result($name, $type);
上面的查询默认运行,当加载index.php时显示所有类型的蔬菜,然后我决定添加一个按钮,改变结果只显示土豆,现在当类型不在url中时它不再显示所有蔬菜,因为WHERE类型=?未设置,如何将默认类型设置为所有类型?
答案 0 :(得分:2)
你需要检查GET参数是否为空,所以试试这个
<a href="index.php?type=potato"><div>click here to select only potato</div></a>
$typesql = $_GET['type'];
if($typesql){
$results = $mysqli->prepare("SELECT name, type FROM artists WHERE type = ?");
$results->bind_param("s", $typesql);
}
else {
$results = $mysqli->prepare("SELECT name, type FROM artists");
}
$results->execute();
$results->bind_result($name, $type);
答案 1 :(得分:1)
检查type
参数是否已设置,并根据该参数更改您的查询。
像这样(未经测试):
if (!empty($_GET['type'])) {
$typesql = $_GET['type'];
$results = $mysqli->prepare("SELECT name, type FROM artists WHERE type = ?");
$results->bind_param("s", $typesql);
} else {
$results = $mysqli->prepare("SELECT name, type FROM artists");
}
$results->execute();
$results->bind_result($name, $type);