duan7007 2015-09-23 05:01
浏览 51
已采纳

从不同的表PHP返回数组

I want to create an function to fetch data from different tables which have different table. Is it possible?

This is my function code

<?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();
}
}
}
?>

and this is for use testing my function

<?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();


?>

but it didn't work. Can someone help me? or explain me more about how it can get and array.

Error:

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
  • 写回答

2条回答 默认 最新

  • doujiyong7604 2015-09-23 05:11
    关注

    First you are return empty array for your function fetch_data. . Return you data outside your while loop

    <?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
    }
    ?>
    

    Second you have to assign your return values form function to variable

    <?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();
    
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题