我的原始SELECT查询工作,但没有插入PHP代码中的变量。
这是我的实际选择查询:
SELECT * FROM `program_list`
WHERE
speciality LIKE '%IM%'
AND (stepone2digit <= 78 OR stepone2digit=0)
AND (stepone3digit <= 189 OR stepone3digit=0)
AND (steptwock2digit <= 78 OR steptwock2digit=0)
AND (steptwock3digit <= 189 OR steptwock3digit=0)
AND (steptwocs = 'PASS' OR steptwocs IS NULL)
AND (steponeattempt <= 1 OR steponeattempt=0)
AND (steptwockattempt <= 1 OR steptwockattempt=0)
AND (steptwocsattempt <= 2 OR steptwocsattempt=0)
AND ((USCEImportance = 'MAND' AND USCENoOfMonths<= '3') OR USCEImportance = 'PREF')
AND (yearsfrompassing >= 2 OR yearsfrompassing=0);
以下是我在PHP中传递它的方式:
$sql = "SELECT * FROM `program_list`
WHERE
speciality LIKE '%%s%'
AND (stepone2digit <= %d OR stepone2digit=0)
AND (stepone3digit <= %d OR stepone3digit=0)
AND (steptwock2digit <= %d OR steptwock2digit=0)
AND (steptwock3digit <= %d OR steptwock3digit=0)
AND (steptwocs = '%s' OR steptwocs IS NULL)
AND (steponeattempt <= %d OR steponeattempt=0)
AND (steptwockattempt <= %d OR steptwockattempt=0)
AND (steptwocsattempt <= %d OR steptwocsattempt=0)
AND ((USCEImportance = 'MAND' AND USCENoOfMonths<= '%s') OR USCEImportance = 'PREF')
AND (yearsfrompassing >= %d OR yearsfrompassing=0)
当我运行原始查询时,它工作正常,但是当我插入变量并从PHP运行它时,不会返回任何结果。
我错过了什么?请帮忙。
答案 0 :(得分:0)
您没有在那里分配'%d'和'%s'(尝试使用var_dump($ sql)调试$ sql)。你应该使用sprintf。例如:
$sql = sprintf("SELECT * FROM `program_list` WHERE speciality LIKE '%%s%'",$speciality);
答案 1 :(得分:0)
我假设您使用sprintf
将%s和%d替换为实际值。
问题在于此代码片段:
speciality LIKE '%%s%'
%%
将替换为单个%
,而最后%
将返回警告或通知,因为%'
对sprintf
无效。您必须使用该语法:
speciality LIKE '%%%s%%'
您的完整查询将是:
$sql = "SELECT * FROM `program_list`
WHERE
speciality LIKE '%%%s%%'
AND (stepone2digit <= %d OR stepone2digit=0)
AND (stepone3digit <= %d OR stepone3digit=0)
AND (steptwock2digit <= %d OR steptwock2digit=0)
AND (steptwock3digit <= %d OR steptwock3digit=0)
AND (steptwocs = '%s' OR steptwocs IS NULL)
AND (steponeattempt <= %d OR steponeattempt=0)
AND (steptwockattempt <= %d OR steptwockattempt=0)
AND (steptwocsattempt <= %d OR steptwocsattempt=0)
AND ((USCEImportance = 'MAND' AND USCENoOfMonths<= '%s') OR USCEImportance = 'PREF')
AND (yearsfrompassing >= %d OR yearsfrompassing=0)";
不要忘记使用sprintf
在查询中插入值。