gpt4 book ai didi

php - 根据表单字段动态选择查询

转载 作者:行者123 更新时间:2023-11-30 23:08:24 25 4
gpt4 key购买 nike

我有一个包含两个字段的表单。用户可以填写其中一个,也可以同时填写两个,并相应地查询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 或两个字段都已填写,则代码可以正常工作。但是,当仅填写第二个字段时,我会收到错误消息:

Couldn't execute query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

如果我回显它正确显示的查询:

SELECT * FROM table WHERE number2 = entered value

非常感谢任何帮助!谢谢!!

最佳答案

你忘记转义值了吗?你可以使用这样的东西

$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

关于php - 根据表单字段动态选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20813805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com