我有一个包含两个字段的表单。用户可以填写其中一个或两个,因此应该查询MySQL数据库。
这是我的php代码:
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}
$data = mysql_query($query) or die("Couldn't execute query. ". mysql_error());
如果填写了number1或两个字段,代码工作正常。但是当只填写第二个字段时,我得到错误:
无法执行查询。您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的''附近使用正确的语法
如果我回显查询,则会正确显示:
SELECT * FROM table WHERE number2 = 输入值
非常感谢任何帮助!谢谢!
答案 0 :(得分:0)
$fields = array();
if(!empty($_POST['number1'])) {
$fields[] = 'number1='.mysqli_real_escape_string($_POST['number1']);
}
if(!empty($_POST['number2'])) {
$fields[] = 'number2='.mysqli_real_escape_string($_POST['number2']);
}
$sql = "SELECT * FROM table WHERE ".implide(" AND ", $fields);
$data = mysqli_query($query) or die("Couldn't execute query. ". mysql_error());
不推荐使用mysql扩展,而是使用mysqli
答案 1 :(得分:0)
试试这个
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
if($set==FALSE)
$query .= " WHERE number2 = ".$number2;
else
$query .= " AND number2 = ".$number2;
}
答案 2 :(得分:0)
我认为你因为作业而得到错误。你写了$ set === TRUE,它的==不=== 错误在这里:
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}