2014-09-24 38 views
2

我正在使用oci_bind_by_name()

oci_bind_by_name($stid, ":post1", $_POST['post1']); 
oci_bind_by_name($stid, ":post2", $_POST['post2']); 
oci_bind_by_name($stid, ":post3", $_POST['post3']); 
oci_bind_by_name($stid, ":post4", $_POST['post4']); 
... 

是否有可能在PHP动态地做到这一点,对所有$_POST键调用同名oci_bind_by_name()

只是为了简化我的代码,因为我有50个左右的电话oci_bind_by_name()

回答

2

它可以用foreach环比$_POST阵列可以简单地完成,使用该密钥作为参数名:

// Bind all in a loop: 
foreach ($_POST as $key => $value) { 
    oci_bind_by_name($stid, ":$key", $value); 
} 

但是,你不能保证客户端发送您在POST的钥匙,你其实想要。

$valid_keys = array(
    'post1', 
    'post2', 
    ... 
    ... 
    'post99' 
); 

然后遍历这些代替,检查,他们在POST实际发送尝试使用它们之前:检查它们对键所组成的数组实际上是有效的在准备好的声明中使用是很重要的,然后。

foreach ($valid_keys as $key) { 
    if (!isset($_POST[$key])) { 
    // ERROR! Needed key was not present in $_POST! 
    // Break the loop if you can't execute the statement... 
    } 
    else { 
    oci_bind_by_name($stid, ":$key", $_POST[$key]); 
    } 
} 

如果您正打算建立动态准备的语句的SQL字符串,它维护的安全参数名的列表,就显得尤为重要。

1

如果你确实使用了一个简单的foreach循环来绑定每个变量,不结合循环变量$值

// Bind all in a loop: but DO NOT use $value 
foreach ($_POST as $key => $value) { 
    oci_bind_by_name($stid, ":$key", $_POST[$key]); 
} 

为了从手动Example 3 of oci_bind_by_name()引证:

foreach ($ba as $key => $val) { 
    // oci_bind_by_name($stid, $key, $val) does not work 
    // because it binds each placeholder to the same location: $val 
    // instead use the actual location of the data: $ba[$key] 
    oci_bind_by_name($stid, $key, $ba[$key]); 
} 
+0

除了将'$ value'到'$ _POST [$键]'这基本上从复制另一个答案。另外我想你应该解释为什么不应该使用'$ value'?我认为这不会带来任何不同。 – MSeifert 2016-04-28 23:46:51

+0

这正是我需要的日期帮助 – Jonnny 2016-07-14 12:53:57