2014-03-29 56 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" 

但是使用这个,你有你的阵列中保持正确的顺序或写在你的函数订货和验证码。

相关问题