在PHP中如何将从一个函数的表中获取数据传递给另一个函数?

  • 回答 (2)
  • 关注 (0)
  • 查看 (138)

我有一个名为tab2的MySQL表。它包含姓名和电话字段

创建了一个名字为 gettabledata():

function gettabledata()
{
    $data = array();
    $query = mysql_query("SELECT * FROM tab2");
    $row = mysql_fetch_assoc($query);
     //Here I am unable to get that how can I pass the fetched data in row 
    //  variable to anywhere this function called.
 //  After update:
     return $row;
}
if(isset($_POST['action']))
{
       $gettab = createtable();//calling the function gettabledata
       //Here I want to get the all data from that table
     // After doing Update:
      foreach($gettab as $row){
        echo $row['name'];
        echo $row['phone'];
     }
}

执行后,得到如下警告:

`

Warning: Illegal string offset 'name' in E:\xampp\htdocs\practive\csvtest.php on line 29
Notice: Uninitialized string offset: 0 in E:\xampp\htdocs\practive\csvtest.php on line 29
Warning: Illegal string offset 'phone' in E:\xampp\htdocs\practive\csvtest.php on line 30
Notice: Uninitialized string offset: 0 in E:\xampp\htdocs\practive\csvtest.php on line 30
Warning: Illegal string offset 'name' in E:\xampp\htdocs\practive\csvtest.php on line 29
0
Warning: Illegal string offset 'phone' in E:\xampp\htdocs\practive\csvtest.php on line 30 `

另外在print_r($gettab),我得到了:

Array ( [name] => [phone] => 0 ) 

它只是从表中的第一个记录。

NAMIHEAPTX4869NAMIHEAPTX4869提问于
宅女have fun……回答于

我一般是这么写的:

$query = mysql_query('SELECT * FROM tab2');
while ($row = mysql_fetch_array($query)) {
    echo $row['name'] . ', ' . $row['phone'] . '<br>';
}
帅的惊动我国计算机大神回答于

试试在结尾添加一个return语句

gettabledata()

代码如下:

    function gettabledata()
    {
        $query = mysql_query("SELECT * FROM tab2");
        $row = mysql_fetch_assoc($query);
        return $row;
    }
    if(isset($_POST['action']))
    {
         $row_arr = gettabledata();//calling the function gettabledata
         foreach($row_arr as $row){
            echo $row['id'];
         }
     }

扫码关注云+社区

领取腾讯云代金券