2014-09-03 84 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