简体   繁体   中英

How to pass the fetch data from table from one function to another function in php

I have a table named as tab2 in mysql. It contains name and phone fields.

I have created a function named as 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'];
     }

}

After Update I am getting warning like:

`
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 `

Also on doing print_r($gettab) , I got:

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

Its just first record from table.

Help me with this.Thanks in anticipation.

You just need to add a return statement at the end of the

gettabledata()

Modify the function with return statement as follows.

    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'];
         }

     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM