我想允许用户通过从下拉列表中选择字段名称来搜索表格,然后在该字段中输入要搜索的字词。我遇到的问题是有些字段是字符串,有些是数字。当我从$ _GET变量构造WHERE子句时,我不知道如何界定搜索词,因为我无法想出一个好方法来确定用户选择的字段是数字还是字符串。
这是搜索表单:
<form action="<?php $_SERVER['PHP_SELF'] ?>">
<label for="search_field">Search:</label>
<select name="search_field">
<?php
$fields = $res->fetch_fields();
foreach($fields AS $f) {
echo '<option value="' . $f->name . '">' . $f->name . '</option>\n';
}
?>
</select>
<label for="search_for">For:</label>
<input type="text" name="search_for" />
<input type="submit" value="Search" />
</form>
php文件处理搜索变量,如下所示:
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
$sql_where = "AND " . $_GET['search_field'] . ' = ' . $_GET['search_for'] . ' ';
}
$sql = $sql . $sql_where;
该查询适用于数字字段,但不适用于字符串字段。我可以在search_for术语周围加上引号,但是数字字段不起作用。必须要有办法做到这一点。有任何想法吗?感谢。
答案 0 :(得分:0)
只需使用is_numeric
函数来确定它是一个数字还是字符串:
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
if(is_numeric($_GET['search_for']))
$sql_where = 'AND ' . $_GET['search_field'] . ' = . $_GET['search_for'] . ';
else{
$sql_where = 'AND ' . $_GET['search_field'] . ' = ' . '.$_GET['search_for'] . ' ';
}
}
答案 1 :(得分:0)
您可以使用is_numeric检查$ _GET [&#39; search_for&#39;]是否为php中的数字
if(isset($_GET['search_field']) and isset($_GET['search_for'])) {
$sql_where = "AND " . $_GET['search_field'] . ' = ' .
(is_numeric($_GET['search_for']) ? $_GET['search_for'] : '"' .
$_GET['search_for'] . '"' ) . ' ';
}
此外,如果您始终使用引号分隔search_for,它将使用数值,您可以尝试它。我只是想向你展示is_numeric函数
答案 2 :(得分:0)
您知道您的代码存在安全问题,不是吗?
但是要解决你的问题就行了
$search_for = is_numeric($_GET['search_for'])?$_GET['search_for']:"'".addslashes($_GET['search_for'])."'";
$sql_where = 'AND `' . $_GET['search_field'] . '` = ' . $search_for . ' ';