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

从一个页面读取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条)

报告相同问题?