我希望$queryText
的值为"field = 'Peter'"
我怎么能这样做?
$_GET['name'] = "Peter";
$queryText = "field = $_GET['name']";
echo $queryText;
答案 0 :(得分:1)
以下是使用您的代码的解决方案:
$_GET['name'] = "Peter";
$queryText = "field = $_GET[name]";
echo $queryText;
数组键周围的单引号会导致错误。删除它们可以使代码按预期工作。
还有其他方法可以做到这一点:
1)连接
$_GET['name'] = "Peter";
$queryText = "field = " . $_GET['name'];
echo $queryText;
2)sprintf()
$_GET['name'] = "Peter";
$queryText = sprintf("field = %s", $_GET['name']);
echo $queryText;
3)大括号
$_GET['name'] = "Peter";
$queryText = "field = {$_GET['name']}";
echo $queryText;
答案 1 :(得分:1)
您可以简单地执行以下操作
$_GET['name'] = "Peter";
$queryText = "field = '" . $_GET['name'] . "'";
echo $queryText;
答案 2 :(得分:0)
你可以迭代如下:
foreach($_GET as $key => $value) {
$queryText = "$key = $value";
echo $queryText;
}
答案 3 :(得分:0)
除了约翰的代码,你也可以使用你的代码:
$_GET['name'] = "Peter";
$queryText = "field = {$_GET['name']}";
echo $queryText;
甚至:
$_GET['name'] = "Peter";
$queryText = "field = ".$_GET['name'];
echo $queryText;
使用字符串连接。
如果您在'
变量中完全删除了GET
,那么这也会有效:
$_GET['name'] = "Peter";
$queryText = "field = $_GET[name]";
echo $queryText;