2014-09-03 136 views
0

我有2個php文件,home.php和db_get.php。 home.php包含db_get.php。在db.php中有一個函數,我在home.php中調用它,它返回一個數組。這個數組然後被轉換成json然後打印到控制檯。我在控制檯上看不到任何東西。我認爲這個函數沒有被調用。無法調用php函數

當我把相同的代碼放在函數內部,並且只包含db_get.php文件時,我看到了json結果。

home.php

<script type="text/javascript"> 

    <?php 
    $parameter = 'Category'; 
    $item_type = 'Grocery'; 
    $db = mysqli_connect('localhost', 'root', 'root' , 'shopping_express'); 
    include 'db_get.php'; 
    $results = getData($parameter, $item_type); 
    ?> 

    var picturesJSON = <?php echo json_encode($results); ?>; 
    console.log("The JSON is " + picturesJSON); 
    loadItemImages(picturesJSON); 
    </script> 

db_get.php

<?php 

    function getData($parameter, $item_type){ 
    $sql_statement = "SELECT * "; 
    $sql_statement .= " FROM items "; 
    $sql_statement .= " WHERE " . $parameter . "= '$item_type' "; 
    $sql_statement .= " WHERE type = 'bag' "; 
    $result = mysqli_query($db, $sql_statement); 
    $outputDisplay = ""; 
    $info=array(); 

    if(!$result) { //error 
     $outputDisplay .= " " .mysqli_errno($db); 
     $outputDisplay .= " " .mysqli_error($db); 
     $outputDisplay .= " " .$sql_statement; 
     $outputDisplay .= " " .mysqli_affected_rows($db); 
    } 
    else{ 
     while($row = mysqli_fetch_array($result,MYSQL_ASSOC)){ 
     array_push($info,$row);}  
    } 

    return $info; 
    } 

    ?> 
+0

是否有任何錯誤?無論是在瀏覽器開發控制檯或源代碼中的PHP錯誤? – Flosculus 2014-09-03 10:03:02

+0

您是否在函數外的任何位置使用$ outputDisplay變量?在這種情況下,使用「global $ outputDisplay;」確保它被正確使用。 – 2014-09-03 10:04:11

+1

是'$ db' global?你甚至有連接嗎? – DanFromGermany 2014-09-03 10:07:51

回答

1
function getData($parameter, $item_type){ 
    global $db, $outputDisplay; 

    // then continue the rest of the function 

(感謝@DanFromGermany爲察覺的$ DB變量這是不是全球性的。)

+0

我有一個全局的$ db變量。編輯代碼。 – user3350648 2014-09-03 18:33:06

+0

你應該把「全局$ db,$ outputDisplay;」在你的功能內。這行不會將變量定義爲全局的,而是意味着這些名稱中的變量指向其外部的變量。 (「全局」關鍵字的定義有點誤導。) – 2014-09-03 18:35:23

+0

感謝您指出,我在函數中添加了行全局$ db。它仍然沒有顯示json。 – user3350648 2014-09-03 19:10:43