This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
                                
                                    (3个答案)
                                
                        
                                9个月前关闭。
            
                    
我正在为flutter应用程序制作一个简单的发布系统,要求它必须将发布另存为JSON文件。我已完成登录,并且与发布相同,但是我试图包含发布该帖子的用户名通过为当前用户qwering并将其写入文件,我具有可以成功回显用户全名的功能,但是我无法以使我将其写入文件的方式存储var

我尝试了一些在var中查询和存储的基本示例,但没有成功,我还尝试返回了函数中具有的$ fullname的var

这是我获取全名的功能(可行):

  public function get_fullname($uid){
    $sql3="SELECT fullname FROM users WHERE uid = $uid";
    $result = mysqli_query($this->db,$sql3);
    $user_data = mysqli_fetch_array($result);

    return $user_data['fullname'];

}


这是我编写json文件的代码(有效):

$todays_date = date("y-m-d h:i:sa");
$data = array(

  'name' =>  $user_data['fullname'],
  'Title' => $Title,
  "post" => $Post,
  'date'=> $todays_date,
  'uid'=> $uid

);
$tittle = $user_data['fullname'] . "_post_on_" . $todays_date . ".json";


    function testfun($tittle, $data)
    {

    $fh = fopen("posts/$tittle", 'w')
    or die("error opening output file");
    fwrite($fh, json_encode($data,JSON_UNESCAPED_UNICODE));
    fclose($fh);
    }

    if(array_key_exists('submit',$_POST)){
       testfun($tittle, $data);
    }


json像这样出来:

name    null
Title   "post test 1"
post    "this is a test"
date    "19-04-28 10:47:13pm"
uid "1"


但我需要这个:

name    "CURENT_USER"
Title   "post test 1"
post    "this is a test"
date    "19-04-28 10:47:13pm"
uid "1"

最佳答案

您的提示$ user_data ['fullname']在函数外为空,请调用函数:

$data = array(

  'name' =>  get_fullname($uid),
  'Title' => $Title,
  "post" => $Post,
  'date'=> $todays_date,
  'uid'=> $uid

);

关于php - 如何进行mysql查询并将其存储在var中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55895260/

10-13 04:29