donglu9898 2014-10-24 23:00
浏览 42
已采纳

变量不会传递给第二个php

I have 3 php files: the first with a form and its validation, the second that stores those values in the db and the third contains the domain, etc. I have tried everything to pass those variables values from the first to second php ex: $_POST , $_Get and isset() as display in the Save.php.

But the values are " " or null (empty) because I echo them in the Save.php and nothing appears. Just gives me messages for each variable as follows - Notice: Undefined index: lname in C:\xampp\blablabla\Save.php on line 5.

The connection is working, the query is working, the validation is working, the form is working. The only problem is when I call

if($valid)
{
    header('Location: Save.php');
    exit();
}

main.php

 <?php
 $nombreErr = "";
 $nombre = "";
 $apellidoErr = "";
 $apellido = "";
 $motivosErr = "";
 $motivos = "";
 $idEstudianteErr = "";
 $idEstudiante = "";
 $segundoAppellidoErr = "";
 $segundoAppellido = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
    $valid = true;
    if (empty($_POST["fname"])) //Nombre Requerido y Solo letras y espacios en blanco
    {
        $nombreErr = "Nombre requerido"; 
        $valid = false;
    } 
    else 
    {
        $nombre = test_input($_POST["fname"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$nombre)) 
        {
            $nombreErr = "Solo letras y espacios en blanco"; 
            $valid = false;
        }
    }

    if (empty($_POST["lname"])) //Apellido Requerido y Solo letras y espacios en blanco
    {
        $apellidoErr = "Apellido Requerido";
        $valid = false;
    }
    else 
    {

        $apellido = test_input($_POST["lname"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$apellido)) 
        {
            $nombreErr = "Solo letras y espacios en blanco"; 
            $valid = false;
        }

    }

    if (empty($_POST["Slname"])) //Segundo apellido solo letras y espacios en blanco
    {
        $segundoAppellido = "";
        $valid = false;
    } 
    else 
    {
        $segundoAppellido = test_input($_POST["Slname"]);
        if (!preg_match("/^[a-zA-Z ]*$/",$segundoAppellido)) 
        {
            $segundoAppellidoErr = "Solo letras y espacios en blanco"; 
            $valid = false;
        }
    }

    if (empty($_POST["studentId"])) //Numero estudiante solo numeros y rayas
    {
        $idEstudianteErr= "";
        $valid = false;
    } 
    else 
    {
        $idEstudiante = test_input($_POST["studentId"]);
        if (!preg_match("/^[0-9-]*$/",$idEstudiante)) 
        {
            $idEstudianteErr = "Solo numeros y \"-\""; 
            $valid = false;
        }
    }

    if (empty($_POST["Motive"])) //Motivos Requeridos
    {
        $motivosErr = "Motivo(s) Requerido(s)";
        $valid = false;
    } 
    if($valid)
    {
        header('Location: Save.php');
        exit();
    }
}
 function test_input($data) {
 $data = trim($data);
 $data = stripslashes($data);
 $data = htmlspecialchars($data);
 return $data;
 }
 ?>

 <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">

            <input type="hidden" name="depName" value="Admisiones">
            <input type="hidden" name="personStat" value="Espera">

            <class="input1">FirstName :<input type="text" name="fname" value="<?php echo $nombre;?>">
            <span class="error">* <?php echo $nombreErr;?></span> <br>

            <class="input2">LastName :<input type="text" name="lname" value="<?php echo $apellido;?>">
            <span class="error">* <?php echo $apellidoErr;?></span> <br>

            <class="input3">Second LastName :<input type="text" name="Slname" value="<?php echo $segundoAppellido; ?>"> 
            <span class="error"><?php echo $segundoAppellidoErr; ?></span> <br>

            <class="input4">Student Id :<input type="text" name="studentId" value="<?php echo $idEstudiante;?>">
            <span class="error"><?php echo $idEstudianteErr; ?></span> <br>


            <select name="Motive[]" multiple="MULTIPLE">

                <?php 
                    $sql1="SELECT categoryName, estimationTime FROM Category where depName='Asistencia Economica'";

                    $result1=mysqli_query($con, $sql1);

                    while($row1 = mysqli_fetch_array($result1)) 
                    {
                        echo"<option value=".str_replace(" ", "_", $row1['categoryName']) .":". $row1['estimationTime'].">".$row1['categoryName']."</option>";
                    }
                ?>
            </select>
            <span class="error">* <?php echo $motivosErr;?></span> <br>

            <input class="button" type="submit" value="Registrate">

        </form> 

Save.php

 <?php
 include('Connection.php');

 $firstname = isset($_POST['fname']);
 $lastname = mysqli_real_escape_string($con,  $_POST['lname']);
 $secondLastName = mysqli_real_escape_string($con, $_POST['Slname']);
 $studentId =mysqli_real_escape_string($con, $_POST['studentId']);
 $depNum= mysqli_real_escape_string($con, $_POST['depName']);
 $status= $_POST['personStat'];
 $mymotives= $_GET['Motive'];
 $motivestring= "";
 $motiveTime= 0;
 echo $firstname . "where are you";
 echo $lastname;
 echo $secondLastName;
 echo $studentId;
 echo $depNum;
 echo $status;
 echo $mymotives;
 if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
 }

$sql ="INSERT INTO List (depName, personName, personLast, secondLast, stuId, personStatus, manyMotive, categoryTime) 
VALUES ('$depNum','$firstname','$lastname', '$secondLastName','$studentId', '$status', '$motivestring', '$motiveTime')";

 if (mysqli_query($con, $sql)) {
 echo "New record created successfully";
 } else {
 echo "Error: " . $sql . "<br>" . mysqli_error($con);
 }

 mysqli_close($con);

 ?>
  • 写回答

1条回答 默认 最新

  • duanluan8390 2014-10-24 23:09
    关注

    This is where it is not working:

    Header('Location: Save.php');
    

    Here you pass control to Save.php, but you do not pass any data... directly. Since it does not work, I gather you're not passing it at all.

    You can do one of these things:

    • if the file that has executed so far has not produced any output, then you can simply include the file Save.php:

      include "Save.php"

    • if you want to pass data directly and it's not a large amount, you can put it in the GET string, but beware, it will appear in clear in the address bar:

      Header("Location: Save.php?name=Vitruvio&surname=Pietrisco&age=67");

    • if you want to pass a larger amount of data, you can use sessions.

      In the first file:

      session_start(); // The very first line

      ...

      $_SESSION['Hello'] = "World";

      In the second file (Save.php):

      session_start();

      echo "You said " . $_SESSION['Hello'];

      will echo 'You said World'.

    Update: normally, you would place the validation in the same file that does the save. Or if you want to decouple the sources, you could wrap all the information in an array, and pass it to a function called Save(). This function could be the only function in the Save.php file. Now you can do:

    $data['firstname'] = $_POST['fname'];
    $data['lastname']  = $_POST['lname'];
    
    // Now you could even put $_SESSION['data'] = $data;
    // and have it all in the session!
    
    ...and also simplify the use of mysql escaping with a cycle:
    
    foreach ($data as $field => $content) {
        $data[$field] = mysql_real_escape_string($con, $content);
    }
    // By the way: IMPORTANT!. mysql_* functions are DEPRECATED and will be REMOVED
    // (maybe soon). Use PDO instead! It takes a bit to adapt, but it's worth it.
    
    if ($valid) {
        // The file is only included if it is necessary, if data are $valid.
        include "Save.php";
        save($data);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码