我试着解释这件事,
我有一个包含20个问题的数据库,有两个原则: 1)心脏病学,2)内分泌。您可以使用HTML选择菜单进行选择,也可以选择所有的概念。
在我的html页面上,我有一个包含3个选项的选择菜单,每个选项都有一个值:
<div id="selectContainer1">
<select id="selectedPrinciple" name="selectedPrinciple">
<option value="" disabled="disabled" selected="selected">Select a System</option>
<option value="">All</option>
<option value="VASCULAR">Cardiology, Vascular System</option>
<option value="ENDOCRINE">Endocrine</option>
</select>
</div>
<input type="submit" value="Start">我在php上有以下代码:
$selectedPrinciple = $_POST['selectedPrinciple'];
$sql = ("SELECT * FROM qbanktable WHERE Principle = '$selectedPrinciple'"现在,当我选择“心脏病学”或“内分泌”选项时,所有与之相关的行都会从我的数据库中选择并显示在下一页。但是,当我选择"All“时,我会得到一个语法错误,因为它没有值,所以在我的数据库中找不到行。我是否可以为mysql返回所有行的" all“选项值设置任何内容?
发布于 2017-01-13 21:49:00
您可以检查$selectedPrinciple是否为empty(),并相应地修改查询。
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// this line indicates that you don't use prepared statements
$sql = "SELECT * FROM `qbanktable` WHERE `Principle` = '$selectedPrinciple'";
} else {
$sql = "SELECT * FROM `qbanktable`";
}使用mysqli准备语句的完整示例
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `qbanktable` WHERE `Principle` = ?");
$stmt->bind_param("s", $selectedPrinciple);
} else {
// prepare
$stmt = $conn->prepare("SELECT * FROM `qbanktable`");
}
// execute
$stmt->execute();
// fetch data
if (!($res = $stmt->get_result())) {
echo "Failed to fetch the result set: (" . $stmt->errno . ") " . $stmt->error;
}
// print data
print_r($res->fetch_all());
// close prepared statement
$stmt->close();
// close connection
$conn->close();发布于 2017-01-13 22:02:53
就我个人而言,我喜欢使用一些技术来“构建”我的查询,如下所示:
注:
我正在演示如何使用PDO和参数绑定来实现这一点,因为您的查询对SQL攻击是开放的。
$sql = "SELECT * FROM `qbanktable`";
$where = [];
$params = [];
if ( ! empty( $_POST['selectedPrinciple'] ) ) {
$where[] = '`Principle` = ?';
$params[] = $_POST['selectedPrinciple'];
}
if ( /* some other condition */ ) {
// add to the $where / $params as appropriate
}
// Glue the $where into a string
$where = implode( ' AND ', $where );
// Append where to the $sql statement
$sql .= ( $where ) ? ' WHERE ' . $where : '';
// assumes $conn is already a set-up PDO connection
$stmt = $conn->prepare( $sql );
$stmt->execute( $params );
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);发布于 2017-01-13 21:55:49
我认为最好的方法是在PHP中签入selectedPrinciple的值是否与ALL类似或为空,然后不要添加查询的WHERE部分。
如果真的想对所有选项使用一些值,您可以尝试使用一个或两个%的符号'%‘或’%‘,但是我不记得它是否有效。然而,我不推荐这种方法。还要注意SQL注入。
https://stackoverflow.com/questions/41643887
复制相似问题