我需要使用分区的编号作为变量的尾端。示例$publish_page_
添加区号
我从我的网址中抓取了$district_num
echo
这是我尝试过的
$district_num = $_REQUEST['district_num']; // from url and works
$publish_page_.''.$district_num = $district_var['publish_page_'.$district_num.'']; //this does not work
$publish_page_.''.$district_num = addslashes($_POST['publish_page_'.$district_num.'']); //this does not work
$sql = "UPDATE districts SET
publish_page_$district_num = '$publish_page_$district_num' //this does not work and throws error "can not find publish_page_ in field list
WHERE district_num ='$district_num'"; //this works when the above code is removed
跟进纠正后的代码......谢谢@cale_b和@Bill Karwin
$district_num = (int) $_REQUEST['district_num'];
$$publish_page = "publish_page_{$district_num}";
$$publish_page = $district_var[ "publish_page_{$district_num}"];
if (isset($_POST['submitok'])):
$$publish_page = addslashes($_POST[$publish_page]);
$sql = "UPDATE districts SET
publish_page_{$district_num} = '$publish_page'
WHERE district_num ='$district_num'";
答案 0 :(得分:2)
如果您想了解PHP's variable variables,请参阅手册(我链接到它)。但实际上你根本不需要它。
注意SQL注入。您的代码容易受到攻击。
由于您使用输入来形成SQL列名,因此无法使用SQL查询参数来解决它。但是您可以将输入转换为整数,这样可以防止SQL注入。
Main
以上是安全的,因为$district_num = (int) $_REQUEST['district_num'];
$publish_page_col = "publish_page_{$district_num}";
转换确保num变量只是数字。它不可能包含任何可能导致SQL注入漏洞的(int)
或'
字符。
对于其他动态值,请使用查询参数。
\
正如下面的@cale_b评论,你应该明白在PHP中,变量可以在双引号字符串中扩展。有关详细信息,请参阅http://php.net/manual/en/language.types.string.php#language.types.string.parsing。