2015-09-23 20 views
2

我想創建一個函數以獲取具有不同表的不同表中的數據。可能嗎?[已解決]從不同表中返回數組PHP

這是我的功能碼

<?php 
// Check connection 

function fetch_data($selectsql){ 
include 'connectdb.php'; 
$result = $conn->query($selectsql); 
if($result->num_rows <= 0){ 
echo "0 results"; 
} 
else{ 
while ($row = $result->fetch_assoc()){ 
return $row = array(); 
} 
} 
} 
?> 

,這是用於測試我的功能

<?php 
include 'fetch_data_test.php'; 
include 'connectdb.php'; 

$selectsql = "SELECT * FROM user"; 
$row = fetch_data($selectsql); 
echo $name = $row["name"]; 
echo $lastname = $row["lastname"]; 
$conn->close(); 


?> 

,但沒有奏效。 有人可以幫我嗎?或者向我解釋更多關於如何獲取和排列的信息。

錯誤:

Notice: Undefined index: name in /var/www/html/home/use_fetch.php on line 7 
Notice: Undefined index: lastname in /var/www/html/home/use_fetch.php on line 8 
+0

首先包括你的連接文件之前,任何 –

+0

什麼是錯誤? –

+0

解析錯誤:語法錯誤,第5行的/var/www/html/home/use_fetch.php中出現意外的T_VARIABLE 我不知道錯誤語法在哪裏 - –

回答

2

首先,你對你的函數fetch_data返回空數組。 。返回您在while循環

<?php 
// Check connection 

function fetch_data($selectsql){ 
$rows=array();// create an array 
include 'connectdb.php'; 
$result = $conn->query($selectsql); 
if($result->num_rows <= 0){ 
echo "0 results"; 
} 
else{ 
while ($row = $result->fetch_assoc()){ 
     $rows= $row;// assign your data to array 
} 
} 
return $rows;// return array 
} 
?> 

第二你必須分配你的返回值的形式功能變量

之外的數據
<?php 
include 'fetch_data_test.php'; 
include 'connectdb.php' 

$selectsql = "SELECT * FROM user"; 
$row=fetch_data($selectsql);// assing into a variable 
echo $name = $row["name"]; 
echo $lastname = $row["lastname"]; 
$conn->close(); 


?> 
+0

非常感謝你hhhh! :D,但你能解釋我更多關於$行和$行使用函數?這將是非常高興的你! :) –

+0

在你的代碼中,你返回一個空的數組,在你的代碼中是錯誤的。在'$ rows'中,你分配了一個空數組。現在,在while循環內傳遞給你'$ row'的結果就是'$ row',並且從你的函數返回'$ rows' – Saty

2

當您需要修復使用此代碼return $row = array();你返回一個空數組。

另外,您並未將返回值保存到任何變量。

在你的代碼來測試你的功能,改變fetch_data($selectsql);$rows = fetch_data($selectsql);

 <?php 
     // Check connection 

     function fetch_data($selectsql){ 

     include 'connectdb.php'; 
     $rows = array();   
     $result = $conn->query($selectsql); 
     if($result->num_rows <= 0){ 
      echo "0 results"; 

     } else{ 
      while ($row = $result->fetch_assoc()){ 
        $rows[] = $row; 
      } 
     } 

     $conn->close(); 
     return $rows; 

     } 

     ?> 

     <?php 
     include 'fetch_data_test.php'; 

     $selectsql = "SELECT * FROM user"; 
     $rows = fetch_data($selectsql); 
     foreach($rows as $row){ 
      echo $name = $row["name"]; 
      echo $lastname = $row["lastname"]; 
      echo "\n"; 
     } 


     ?> 
+0

仍然會得到相同的錯誤。 解析錯誤:語法錯誤,第5行的/var/www/html/home/use_fetch.php中的意外T_VARIABLE –

+0

我無法爲我獲取數據。 –

+0

我已將代碼添加到我的答案中,並刪除了所有不必要的代碼。這會給你所有由你的代碼取得的結果 –