2014-09-24 36 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