2014-07-07 110 views
0

我試圖定義一個function來執行Oracle查詢並動態地使用接收到的string變量將模式設置爲oci_fetch_array()。這是函數:PHP警告:oci_fetch_array()期望參數2很長,給出的字符串爲

public function db_single_select($conn,$select,$table,$condition,$fetch_mods='') { 

    //A string should be sent to "$fetch_mods" with this format: mode1+mode2+etc... 
    //If a value is not passed to '$fetch_mods', it will be the default fetch mode 

    $sql = oci_parse($conn, "select $select from $table where $condition"); 
    $sql_result = oci_execute($sql, OCI_DEFAULT); 
    if($sql_result){ 
     if(empty($fetch_mods)) {      
      $res = oci_fetch_array($sql); 
     } 
     else{ 
      $res = oci_fetch_array($sql, $fetch_mods); 
     }     
    } 
    else{ 
     $res = FALSE; 
    }    
    oci_free_statement($sql); 
    return $res; 
} 

我這樣調用該函數:

db_single_select($conn, $select, $table_name, $condition, 'OCI_ASSOC');

我得到這樣的警告:

Warning: oci_fetch_array() expects parameter 2 to be long, string given in db_connect.php on line 61

我知道,第二個參數(模式)對於oci_fetch_array()應該是數字的,因爲它在PHP文檔中是這樣說的。 http://www.php.net/manual/en/function.oci-fetch-array.php

問題是如何根據函數接收的變量設置模式?

既然你可以通過與像

$row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS);

一個+標誌他們分隔條件多種模式,有一個簡單的方法,包括接收OCI_ASSOC+OCI_RETURN_NULLS一個字符串中的功能,並設置與模式?

+1

'OCI_ASSOC'等是常數;使用它們不帶引號,即'db_single_select($ conn,$ select,$ table_name,$ condition,OCI_ASSOC + OCI_RETURN_NULLS)' – Phil

+0

沒錯!謝謝 – Masoud

回答

1

你似乎誤解了什麼constants實際上是。在OCI_ASSOC(和其他OCI constants)的特定情況下,它表示一個簡單的整數值。這可以通過var_dump(OCI_ASSOC);的輸出int(1)來證明。組合常數(如OCI_ASSOC+OCI_RETURN_NULLS)是一個簡單的加法運算,結果爲int(5)

爲了讓你的函數的工作,你應該簡單地直接傳遞常數通過去除周圍撇號:

db_single_select($conn, $select, $table_name, $condition, OCI_ASSOC); 

安全警告:

您的代碼很容易受到SQL Injection(還看什麼PHP manual says about it)。你應該使用parameter binding來減輕攻擊的可能性。

+0

感謝您的回答。關於SQL注入,好點,但這是一個內部函數,輸入不是來自用戶。 – Masoud

-1

您必須確定連接是否成功。 檢查退貨是否是資源$conn在您的代碼中。

希望對您有所幫助。

相關問題