du59131 2015-02-17 21:59
浏览 54

为什么PHP变量仍未定义?

I am working with three PHP files. Two serve as web pages and the other in an external server side script. The server side script is included in both web pages files and what I want to do is have some buttons on the first page and depending on which one is clicked, populate the second page with data and then redirect to it.

With the code below, the idea was to pick up the button click, figure out which button was clicked, and then call the function to run the proper query and set the needed variables. I don't understand why the variable is not getting set.

Thanks to anyone looking at this!

First page's button (index.php):

<input type="submit" id='details' name='details' value='Submit'/>

Second page where variable is undefined when page is loaded:

<h4><?php echo $selected_button; ?></h4>

External script:

function detailBuilder(){

    $selected_button = "Option One";
    //header('Location: details.php'); if this is here, the page still redirects but the variable doe not get set
    //More will happen here once it works

}

if(isset($_POST['details'])){

    detailBuilder();
    header('Location: details.php');

}
  • 写回答

1条回答 默认 最新

  • dongyiluan1718 2015-02-17 22:25
    关注

    As several people have pointed out previously, you redirect to another file. At that point, all locally defined variables are gone - you no longer have access to them.

    Look into PHP sessions in PHP's documentation. Sessions will allow you to transfer these variables from request to request. However, sessions will only work if you are running some form of webserver.

    UPDATE: Also to note, as other people (once again) have pointed out, $selected_button = "Option One" will ONLY apply inside the "scope" of the function detailBuilder. So calling detailBuilder() creates a variable called $selected_button inside the function, and then immediately discards it.

    UPDATE 2.0: Sorry for so many updates. Here's an example of setting a session:

    Update 3.0: updated code slightly

    First things first. Make sure you start the session.

    session_start();
    

    You're going to have to call session_start() at the start of any php script! That means that the first file that executes every time should have session_start() at the top.

    External Script:

    $_SESSION["selected_option"] = "Option One";
    

    Script where originally it was undefined:

    $selected_details  = $_SESSION["selected_option"];
    ?>
    <h4><?=$selected_details?></h4>
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?