duankeye2342 2015-06-24 02:23
浏览 70
已采纳

从一个页面读取PHP全局变量,在另一个页面中打印(在同一个PHP类中)

I was wondering why my code, which can be trimmed down to the following structure, isn't printing what I think should be printed. Basically I have two methods and two corresponding html pages in the same php controller class. I want to retrieve the value of the POST request (html text input form) from mypage.html and print that in secondpage.html to which we are redirected when the user clicks 'submit' button after typing in their input in the text box.

Update: I just read about PHP sessions and my program does start sessions. But should I use sessions even if the user input date is saved in the database?

<? php 

$var; // initializing global variable; 

class MyClass { 

   public function mypage () { 
      global $var; 
      $var = $_POST['form_name']; 
   } 

   public function secondpage () { 
      global $var; 
      print_r($var); 
   } 

}
  • 写回答

2条回答 默认 最新

  • duanlai1855 2015-06-24 02:37
    关注

    The simplest would be to store the value in the session, like

    <? php 
    class MyClass { 
    
       public function mypage () { 
          $_SESSION['var'] = $_POST['form_name']; 
       } 
    
       public function secondpage () { 
          print_r($_SESSION['var']); 
       } 
    
    }
    

    This expects the session to be started by calling session_start() somewhere else, but you said the session is started.

    But having the data saved in database, why don't you read it back in the secondpage()?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建