2016-12-11 151 views
1

假設我有一個名爲mytable的與列的表:函數返回的查詢結果

------------------------ 
| id | field1 | field2 | 
------------------------ 

,並假設我有一個HTML文件:

<body> 
<?php 
    include ('connect-db.php'); 
    include ('function.php'); 
?> 

<ul> 
    <?php 
     myfunction(); 

     while($row = $result->fetch_assoc()){ 
      echo "<li>".$row['field1']." and ". $row[field2]."</li>"; 
     } 
    ?> 
</ul> 
</body> 

這是我的connect-db.php文件:

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname  = "dbname"; 

$conn=new mysqli($servername, $username, $password, $dbname); 
?> 

這是我的function.php文件:

<?php 
    function myfunction(){ 
     $sql = "SELECT * FROM mytable"; 
     $result = $conn->query($sql); 
    } 
?> 

如何回顯字段1和字段2?因爲我有和錯誤

+0

提供你的錯誤,請 – demo

回答

0

函數內部使用的任何變量默認限制爲本地 函數作用域。

您可以在這裏閱讀更多關於它的信息:Variable scope。如何解決它?通過$conn作爲參數myfunction,並返回$result

function myfunction(mysqli $conn) { 
    $sql = "SELECT * FROM mytable"; 
    return $conn->query($sql); 
} 

,那麼你可以在主界面

<body> 
    <?php 
     include ('connect-db.php'); 
     include ('function.php'); 
    ?> 

    <ul> 
     <?php 
     $result= myfunction(); 

      while($row = $result->fetch_assoc()){ 
       echo "<li>".$row['field1']." and ". $row[field2]."</li>"; 
      } 
     ?> 
    </ul> 
    </body> 

$result = myfunction($conn); 
0

稱它爲確保以下變化.....

在你的函數文件..

 <?php 
     include ('connect-db.php'); 
     function myfunction(){ 
      $sql = "SELECT * FROM mytable"; 
      $result = $conn->query($sql); 
      return $result; 
     } 
    ?> 
+0

在主頁你必須定義變量,必須捕捉函數返回的結果。 –

+0

在函數頁面中,您必須包含數據庫連接文件以查詢數據庫......這些常見錯誤.... –