2017-10-17 38 views
1

我需要使用區號作爲變量的尾部。例如$publish_page_加區號 我抓住從我的URL $district_num我已經與echoPHP在變量中使用mysql發佈變量

在此間證實是什麼,我已經試過

$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 

校正碼跟進......謝謝如果你想了解PHP's variable variables您@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'"; 
+1

更有用的是_examples_的輸入和輸出。你的問題有點混亂。然而,你正在尋找兩個概念:1:變量變量和2:插值 - 爲你的第二行嘗試:'$ key =「publish_page _ {$ district_num}」;'then'$$ key = $ district_var [「 publish_page_4 _ {$ district_num}「];' - (yes,'$$ key' - 這是一個變量變量) –

回答

2

,它的手冊中(我鏈接到它)。但你實際上並不需要你的情況。

注意SQL注入。你的代碼容易受到攻擊。

由於您使用輸入形成SQL列名,因此無法使用SQL查詢參數來解決該問題。但是您可以將輸入轉換爲整數,這樣可以防止SQL注入。

$district_num = (int) $_REQUEST['district_num']; 

$publish_page_col = "publish_page_{$district_num}"; 

以上是安全的,因爲(int)鑄造確保num變量是隻有數字。它不可能包含任何可能導致SQL注入漏洞的字符,如'\

對於其他動態值,請使用查詢參數。

$publish_page_value = $_REQUEST["publish_page_4{$district_num}"]; 

$sql = "UPDATE districts SET 
     `$publish_page_col` = ? 
     WHERE district_num = ?"; 
$stmt = $pdo->prepare($sql); 
$stmt->execute([ $publish_page_value, $district_num ]); 

由於@cale_b註釋如下,您應該明白,在PHP中,變量可以在雙引號字符串內展開。有關詳情,請參閱http://php.net/manual/en/language.types.string.php#language.types.string.parsing

+0

您可能會提到雙引號的重要性以及插值在它們內部發生的事實...... –

+0

回顯下面的代碼文本丟失,只顯示數字。 $ district_num =(int)$ _REQUEST ['district_num']; \t $ publish_page_col =「publish_page _ {$ district_num}」; – iconMatrix

+0

它適合我。我可以'var_dump($ publish_page_col);'和輸出是'string(17)「publish_page_1234」'。我不知道你在做什麼。 –