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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。