2014-03-29 55 views
2

將可變數量的參數傳遞給php函數的最佳方式是什麼?我的意思是,假如我有以下幾點:將可變數量的參數傳遞給php函數的最佳方式

function my_func($a, $b, $c) { 
    $q = 'SELECT ' . $a . ' FROM ' . $b . ' WHERE status IS NULL'; 
} 

my_func('id', 'table'); 
my_func('id', 'table', ' AND x = 1'); 

我讀過有關func_get_arg(),但如果我在第一種情況下調用func_get_arg(2),我會得到一個,Argument 2 not passed to function錯誤。

重要提示:該查詢不是用用戶傳遞的參數執行的,所以沒有注入攻擊!它由我提供的受控參數執行,其功能是檢查該值是否在外鍵組合內有效!所以請不要諷刺「注入天堂」的評論,謝謝。

+8

請不要使用字符串連接形成SQL。請改用參數化或準備好的查詢。 – Dai

+1

你可以設置一個數組作爲變量,在那裏你可以設置多達你想要的數字 –

+3

SQL注入天堂 –

回答

1

既然你提到你的函數不處理用戶傳遞的參數..我建議僅供參考這個..

:我只是用那裏面的echo用於演示目的..你可以稍後改變。

<?php 
function my_func() { 

    echo $q = 'SELECT ' . func_get_arg(0) . ' FROM ' . func_get_arg(1) . ' WHERE status IS NULL'; 
} 

my_func('id', 'table'); 

上面顯示...

SELECT id FROM table WHERE status IS NULL 

的參數從0指數開始,所以你應該做的.. func_get_arg(1)獲得第二個參數。

+0

嗨尚卡爾,也許我不是清楚,但這是我第一次嘗試(你可以在代碼後面的問題中閱讀它)。問題是可能有2個或更多可能的參數傳遞,所以如果我使用'func_get_arg(2)'我會得到一個PHP錯誤... – Mariano

+0

爲什麼不使用'func_get_args()'返回數組中的所有參數,你使用'func_num_args'來知道有多少個參數通過,你可以相應地編寫你的腳本......對吧? –

+0

好的......有道理......但在這一點上傳遞數組並不容易? – Mariano

2

嗯,我不知道是否最好,但我想通過數組作爲參數,然後在我的函數中使用它。這裏有一個例子:

function my_query($query = array()) 
{ 
    // select and from are required to exist 
    if(!empty($query) && array_key_exists('select', $query) && array_key_exists('from', $query)) 
    { 
     $q = "select {$query['select']}"; 
     $q .= " from {$query['from']}"; 

     foreach($query as $key => $val) 
     { 
      // Don't want to include select and from once again (also do not unset before in case need to run all of this once again) 
      if($key != 'select' && $key != 'from') 
      { 
       // Search if key has underscore and replace it with space for valid query 
       if(strpos($key, '_') !== false) 
        $key = str_replace('_', ' ', $key); 

       // Build query with spaces and all 
       $q .= " " . $key . " " . $val; 
      } 
     } 

     // Run query here using $q 
    } 
} 

而且你可以在陣列傳遞,只要你喜歡:

$query = array(
    'select' => '*', 
    'from'  => 'users', 
    'where'  => 'age > 25', 
    'order by' => 'id' 
); 

// Or 
$query = array(); 

$query['select'] = '*'; 
$query['from'] = 'users'; 
$query['where'] = 'age > 25'; 
$query['order_by'] = 'id'; 

my_query($query); 

// Would return us something like this 
string(46) "select * from users where age > 25 order by id" 

但是使用這個,你有你的陣列中保持正確的順序或寫在你的函數訂貨和驗證碼。

相關問題