2011-11-05 38 views
-1

我想要一個SelectAll函數,它接受幾個參數(類,表,排序字段和排序順序)。註釋說明正在發生什麼(或者應該怎麼做)。未定義的索引僅當使用數組時

public static function SelectAll($class, $table, $sort_field, $sort_order = "ASC") 
    { 

    /* First, the function performs a MySQL query using the provided arguments. */ 

    $query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order; 
    $result = mysql_query($query); 

    /* Next, the function dynamically gathers the appropriate number and names of properties. */ 

    $num_fields = mysql_num_fields($result); 
    for($i=0; $i < ($num_fields); $i++) 
    { 
     $fetch = mysql_fetch_field($result, $i); 
     $properties[$i] = "'".$fetch->name."'"; 
    } 
    /*echo [$properties[0]; echo "<br />";}*/ 
    /* Finally, the function produces and returns an array of constructed objects. */ 

    while($row = mysql_fetch_assoc($result)) 
    { 
     for($i=0; $i < ($num_fields); $i++) 
     { 
     $args[$i] = $row[$properties[$i]]; 
     } 
     $array[] = call_user_func_array(new $class, $args); 
    } return $array; } 

現在,我遇到的問題是,$row[$properties[$i]]會導致「未定義指數」。

右鍵功能集數後/在一個數組中的字段,並將它們的名字,我可以呼應$properties[0]值,並將其顯示爲它應該,「ID」,但$row[~anything here~]根本不會手動,除非我的工作輸入值,如$row['id']。正如你可以想象的那樣令人沮喪和困惑。

爲什麼不能工作?是否有任何解決方案或完成此功能的替代方法?

回答

0

當我看到你的$properties[$i]數組項有引述值一樣"'id'", 所以$row[$properties[$i]] < ==>$row["'id'"] = $row["id"]!;

,你可能想後$result = mysql_query($query);

檢查$result === false無論如何,我認爲你可以取代你的函數這個(除非你只建造它演示):

public static function SelectAll($class, $method_name, $table, $sort_field, $sort_order = "ASC"){ 
    /* First, the function performs a MySQL query using the provided arguments. */ 
    $query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order; 
    $result = mysql_query($query); 

    while($row = mysql_fetch_array($result)) 
    $array[] = call_user_func_array(array($class,'__construct'), $row); 

    return $array; 
} 
+0

感謝您回覆:當我回聲'$ properties [0]',等等,我得到''id''的價值。通過這種方式,'$ properties [0]'看起來等於''id'',所以'$ row [$ properties [$ 0]]'應該等於'$ row ['id']''。也許你只是看到用來包圍字符串的引號,因爲它將'$ fetch-> name'的兩個撇號連接起來。 – tuespetre

+0

但是你爲什麼使用撇號,爲什麼不使用'$ properties [$ i] = $ fetch-> name;'? – biziclop

+0

我明白你的意思了。謝謝!通過調用'$ row [$ properties [$ i]]'解決了這個問題,儘管現在看起來我從call_user_func_array中有一個錯誤:'Product類的對象無法轉換爲字符串'...這就是它的方式去,我想... – tuespetre