【发布时间】:2014-03-08 15:19:10
【问题描述】:
我正在使用 PHP 和 MYSQL 进行作业。
其中一项任务是搜索字段的任意组合。这包括从数据库填充的下拉框。和文本字段。
t2ath 包含
ID
SPORT
COUNTRY
GENDER
FIRSTNAME
LASTNAME
Image
我已经在这个代码上工作了一个星期,以便能够搜索任何组合而不会出现错误。
我想知道是否还有其他更有效的方法。
$selectedSport = $_POST['sport']; $gender =$_POST['gender']; $fName =$_POST['fname']; $lName =$_POST['lname']; $country =$_POST['country'];
$sql_fName=""; $sql_lName=""; $sql_gender=""; $sql_sport=""; $sql_country="";
$checkFiled=False;
$where="";
$and="";
//
if ( $selectedSport=="showAll")
{
!isset($selectedSport);
}
else
{
if (isset($selectedSport))
{
if ($checkFiled==True)
{
$sql_sport = " AND t2ath.sport = '$selectedSport'" ;
}
else
{
$sql_sport = " t2ath.sport = '$selectedSport' " ;
$checkFiled=True;
}
}
else {
$sql_sport = "";
}
}
//
if ( $country =="showAll")
{
!isset($country);
}
else
{
if (isset($country))
{
if ($checkFiled ==True)
{
$sql_country = " AND t2ath.country = '$country'" ;
}
else
{
$sql_country = " t2ath.country = '$country' " ;
$checkFiled=True;
}
}
else {
$sql_country = "";
}
}
//
if ( $gender=="Gender")
{
!isset($gender);
}
else
{
if (isset($gender))
{
if ($checkFiled ==True)
{
$sql_gender = " AND t2ath.gender = '$gender'" ;
}
else
{
$sql_gender = " t2ath.gender = '$gender' " ;
$checkFiled=True;
}
}
else {
$sql_gender = "";
}
}
//
if ($fName =="")
{
!isset($fName);
}
else
{
if (isset($fName))
{
if ($checkFiled==True)
{
$sql_fName = " AND t2ath.firstName = '$fName'" ;
}
else
{
$sql_fName = " t2ath.firstName = '$fName' " ;
$checkFiled=True;
}
}
else {
$sql_fName = "";
}
}
//
if ($lName =="")
{
!isset($lName);
}
else
{
if (isset($lName))
{
if ($checkFiled==True)
{
$sql_lName = " AND t2ath.lastName = '$lName' " ;
}
else
{
$sql_lName = " t2ath.lastName = '$lName' " ;
$checkFiled=True;
}
}
else
{
$sql_lName = "";
}
}
if ($checkFiled == True)
$where=" where ";
$selectString = "SELECT t2ath.lastName,t2ath.firstName,t2ath.image,t2ath.sport,t2ath.gender,t2ath.country,t2country.flag FROM t2ath LEFT JOIN t2country
ON t2ath.country = t2country.name $where $sql_sport $sql_country $sql_gender $sql_fName $sql_lName ";
$result = mysql_query($selectString);
【问题讨论】:
-
如果您现在只是学习,请停止使用已弃用的 mysql 扩展并使用 mysqli (us1.php.net/manual/en/book.mysqli.php) 扩展。除其他外,它还支持准备好的语句,这将使您的代码更易于管理。此外,代码
!isset($lName);不会取消设置变量,它会返回变量是否已设置。要取消设置变量,请使用unset($lName); -
为什么需要取消设置这些变量?您永远不会在
if块之外引用它们。 -
@Anthony 实际上,像这样动态生成的 SQL 对于 mysqli 准备好的语句来说更难,因为很难用一组动态参数调用
mysqli_stmt_bind_params。这种类型的事情在 PDO 中要容易得多,因为您可以使用参数数组。 -
参数不需要是动态的。这有点令人费解,但是您因为有一组有限的字段和值可供比较,在值为“全部”的情况下,可以修改输入以简单地将这些留空(让下拉菜单显示“全部' 并且值为空),然后对
WHERE (sport = $sport OR $sport = '')进行查询检查,当值为空时将返回所有行,并在设置时返回匹配项。而且你不应该阻止任何人使用 mysql api 以外的东西。我不在乎他们是切换到PDO还是MYSQLI,目标是切换。