简体   繁体   English

PHP MYSQL:如何保持变量活着直到连接结束

[英]PHP MYSQL : how to keep the variable alive till connection ends

i want to keep some variable alive so that it is available to all the pages of the site ; 我想保留一些变量,以便它可用于网站的所有页面; i tried global but that don't work with these kind of problem ; 我试过全球但是不能解决这些问题; i use the following code : 我使用以下代码:

 while($result1 = mysql_fetch_array( $result)) 
  {   
  $adm_no = $result1['adm_no']; 
  $adm_dt = $result1['adm_dt']; 
  $name = $result1['name']; 
  $dob = $result1['dob']; 
  $f_name = $result1['f_name']; 
  $f_office = $result1['f_office']; 
  $f_o_no = $result1['f_o_no']; 
  $m_name = $result1['m_name']; 
  $m_office = $result1['m_office']; 
  $addr = $result1['addr']; 
  $pho_no = $result['pho_no'];

these same variable in another page called tc.php . 这个相同的变量在另一个名为tc.php的页面中。 how can i do that ???? 我怎样才能做到这一点 ????

Use 采用

$_SESSION['myvar']= "your value";

echo $_SESSION['myvar']; 

will can access any page 将可以访问任何页面

If you want to access all that data again in another page I would recommend storing the information needed to retrieve data from your mysql table in a session rather than the result of the query. 如果您想在另一个页面中再次访问所有数据,我建议在会话中存储从mysql表中检索数据所需的信息,而不是查询结果。 This means you don't have a load of trivial data in your session space. 这意味着您的会话空间中没有大量繁琐的数据。 For example. 例如。

Imagine I have a person table and want to get bits of information for that person on different pages I just store the person_id in a session like so: 想象一下,我有一个人员表,想要在不同的页面上获取该人的信息,我只是将person_id存储在会话中,如下所示:

//home.php
$_SESSION['personID'] = $personID;

Then on any page I want to retrieve person information on I just get the person id from the session and run the query to get the specific information I need. 然后在任何页面上我想要检索人员信息我只是从会话中获取人员ID并运行查询以获取我需要的特定信息。

//profile.php
$personID = $_SESSION['personID'];

//Get specific information here

If you really cant change the way that you are doing this which I really hope you can as it'll make your life a hell of a lot easier then just changing your code to this: 如果你真的不能改变你这样做的方式,我真的希望你能做到这一点,因为它会让你的生活变得更加容易,只需将你的代码更改为:

//make sure that you have started a session at the top of your page before you do anything else
session_start();

while($result1 = mysql_fetch_array($result)) {   
    $_SESSION['adm_no'] = $result1['adm_no']; 
    $_SESSION['adm_dt'] = $result1['adm_dt']; 
    $_SESSION['name'] = $result1['name']; 
    $_SESSION['dob'] = $result1['dob']; 
    //etc
}

Fetch data again in tc.php - it is the best way in this case I think. tc.php再次获取数据 - 在这种情况下,我认为这是最好的方法。

You can also set that data to the session, and in tc.php get it from there. 您也可以将该数据设置为会话,并在tc.phptc.php获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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