【问题标题】:PHP pass variable received from form html to two php files从表单 html 接收到的 PHP 传递变量到两个 php 文件
【发布时间】:2020-07-03 14:21:24
【问题描述】:

我是 php 新手,我正在尝试从 html 获取 POST 值并传递到两个 PHP 文件,其中

  • 第一个执行查询;
  • 第二次详述查询;

所以代码html:

<form action="ExecSelect.php" method="post">
<div class="row form-group">
<div class="col-md-6">

ExecSelect.php:

<?php
include 'connection.php';
include 'select_querys.php';

// Initialize the session 
session_start(); 
       
$SS_IdProduct = $_POST['IdProduct'];
$_SESSION['$SS_IdProduct'] = $SS_ProdSelect;


// switch($_POST['IdProduct']){
switch($_POST['IdProduct']){
    case 'Conecta':
Echo "Something 1"
    break;
    case 'Radar':
Echo "Something 2"
    break;
    default:
        echo 'ERRO! page1';
    }
?> 

而 select_querys.php 是:

<?php
include 'connection.php';

//On page 2
$SS_ProdSelect = $_SESSION['$SS_IdProduct'];

switch($_GET['$SS_ProdSelect']){
    case 'Conecta':
//get results from database
$result = mysqli_query($conn,"SELECT 1;");
$all_property = array();  //declare an array for saving property

    case 'Radar':
//get results from database
$result = mysqli_query($conn,"SELECT 2;");
$all_property = array();  //declare an array for saving property
    break;
    default:
        echo 'ERRO! pagina selct PHP!';
    }
?>

我做错了什么?

【问题讨论】:

  • What I'm doing wrong? 之前我真的没有看到任何问题......你做错的一件事是你的include 'select_querys.php'; 出现在你的session_start() 之前。

标签: php forms variables session


【解决方案1】:

您在顶部包含此文件:

include 'select_querys.php';

所以它在 之前执行:

$SS_IdProduct = $_POST['IdProduct'];
$_SESSION['$SS_IdProduct'] = $SS_ProdSelect;

因此,在执行时没有定义任何内容。 (当时会话还没有开始。)

由于该值预计在 POST 数组中,因此在您的 select_querys.php 中,您可以像在 ExecSelect.php 中一样简单地从 $_POST['IdProduct'] 中读取值:

$SS_IdProduct = $_POST['IdProduct'];

所以你甚至不需要在这里使用会话,除非你打算在未来的请求中使用那个会话值。

请注意,如果您在两个文件中定义了相同的变量(在本例中为 $SS_IdProduct),那么当在相同的上下文中执行这些文件时(如您在此处所做的那样),该变量的第二个声明将覆盖任何更改以前做过。这不会在这里发生,但在您继续更新代码时需要注意一些事情。

(此时还值得注意的是,您甚至没有在select_querys.php使用 $SS_ProdSelect,但我假设您计划在某个时候使用。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2014-02-03
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多