如何使这种情况在php中起作用?
不工作的情况(我要工作的情况): 我有一个表,用于存储要在我的php代码中使用的where子句。
它作为字符串存储在表的字段"WHERECLAUSE"
中:
"where WEEK = '$weeknum' AND YEAR = '$year'"
我从表字段“ WHERECLAUSE”中选择一个字符串值并放入变量
php代码:
$TABLE = 'REASSORT';
$whereclause = "where WEEK = '$weeknum' AND YEAR = '$year'";
// create the select query
$query = "select * FROM $TABLE " . $whereclause;
当我echo $query
收到->
select * FROM REASSORT where WEEK = '$weeknum' AND YEAR = '$year'
由于变量$weeknum
和$year
呈现为字符串,因此它不返回表“ REASSORT”中的数据。
我希望的工作情况:
PHP代码:
$whereclause = " where WEEK = '$weeknum' AND YEAR = '$year' ";
$query = "select * FROM $TABLE " . $whereclause;
当我回显$ query时,我得到->
select * FROM REASSORT where WEEK = '4' AND YEAR = '2019'
并且数据从表“ REASSORT”返回
预先感谢您的帮助。
答案 0 :(得分:0)
尝试将$weeknum
和$year
放在双引号(“)而不是单引号(')中,如下所示
$whereclause = 'where WEEK = "$weeknum" AND YEAR = "$year";
作为单引号下的变量,将被视为字符串而不是变量。
答案 1 :(得分:0)
请用双引号(“)替换单引号(')
替换
$whereclause = " where WEEK = '$weeknum' AND YEAR = '$year' ";
使用
$whereclause = ' where WEEK = "$weeknum" AND YEAR = "$year" ';
答案 2 :(得分:0)
PHP无法将'$weeknum'
和'$year'
识别为变量。您应该尝试使用eval()
,但请谨慎使用此功能。
$weeknum = 5;
$year = 2019;
$whereclause = "where WEEK = '$weeknum' AND YEAR = '$year'";
eval("\$whereclause = \"$whereclause\";");
$query = "select * FROM $TABLE " . $whereclause;
$ query然后应输出:
"select * FROM REASSORT where WEEK = '5' AND YEAR = '2019'"
或使用花括号代替单引号。
所以代替:
'$weeknum'
和'$year'
应该是
{$weeknum}
和{$year}
有关eval()
的详细信息,请参阅:
http://php.net/manual/en/function.eval.php
有关使用大括号的信息,请参见: https://www.phpknowhow.com/basics/usage-of-brackets/
答案 3 :(得分:0)
您需要使用eval
来强制PHP将变量的值替换为$whereclause
字符串。但请注意,如果您不知道值可能是eval
,可能会很危险。这将起作用:
$query = "select * FROM $TABLE " . eval("return \"$whereclause\";");
echo $query;
输出:
select * FROM REASSORT where WEEK = '4' AND YEAR = '2019'