douhengdao4499 2017-08-01 13:41
浏览 41
已采纳

使用PDO发送数据后重定向到空白页

I have a survey webpage that if users done it , I will send the data they give (as $_SESSION from the other pages) and I will change his/her status to 0 (They can't do the survey after that with his/her login info.).

All of these are doing with PDO. But why the page always redirects to a white blank page?

Here is my code

<?php
session_start();
if (!isset($_SESSION['user'])) 
{
header("location:index.php");
}
?>

<?php
require_once "condb.php";
?>

<?php
if (isset($_POST['BTN_P2']))
{
  $_SESSION['problem'] = $_POST['problem'];
  if ($_SESSION['problem'] == "yes"){header("location:survey_3.php");}
else
{
  $sql="INSERT INTO data(time,suggest,phone,eat,problem) VALUES(?,?,?,?,?)";
  $stm=$cn->prepare($sql);
  $stm->bindParam("1",$_SESSION['time']);
  $stm->bindParam("2",$_SESSION['suggest']);
  $stm->bindParam("3",$_SESSION['phone']);
  $stm->bindParam("4",$_SESSION['eat']);
  $stm->bindParam("5",$_SESSION['problem']);

  try 
  {
    $stm->execute();
      try 
      {
       $sqlstatus="INSERT INTO login(status) VALUES(0)";
       $stmt=$cn->prepare($sqlstatus);
       $stmt->execute();
       echo "Finish!";
       header('location:finish.php');
      } 
      catch (Exception $error) 
      {
        echo $error->getTraceAsString();
      }
  } 
  catch (Exception $e) 
  {
    echo $e->getTraceAsString();
  }
}
}
?>

What I am missing?

Edit #1 : Verifying how $_SESSION['user'] comes from.

<?php
if (isset($_POST['BTN_ENTER']))
{
  $username=$_POST['username'];
  $password=$_POST['password'];
  $hashed_password=password_hash($password,PASSWORD_DEFAULT);
    try
    {
      $stmt = $cn->prepare("SELECT * FROM login WHERE username=:username LIMIT 1");
      $stmt->execute(array(':username'=>$username));
      $result=$stmt->fetch(PDO::FETCH_ASSOC);
      if($stmt->rowCount() > 0)
        {
          if(password_verify($password, $result['password']))
          {
            if ($result['status']==1)
              {
                $_SESSION['user']=$result['name'];
                header('location:survey.php');
              }
          }
        }
     }
     catch(PDOException $e)
     {
       echo $e->getMessage();
     }
}
  • 写回答

1条回答 默认 最新

  • drphfy1198 2017-08-01 15:51
    关注

    You should try and break your scripts into functions / methods to make it easier to work with, read, reuse, etc. When you make a function, you can try it manually by itself before you implement it. Once you confirm the function works by itself, then you throw it into the logic and if something fails, you know it's not that function:

    /functions/suggestEatingProblem.php

    <?php
    function suggestEatingProblem($con,$array)
        {
            $sql = "INSERT INTO `data` (`time`,`suggest`,`phone`,`eat`,`problem`) VALUES(?,?,?,?,?)";
            $query = $con->prepare($sql);
            # Since you are not really doing anything special with your parameters
            # just do the array into the execute function, it's more straight forward
            $query->execute($array);
        }
    

    /functions/addLoginStatus.php

    <?php
    function addLoginStatus($con,$val)
        {
            # Don't need to prepare, just query
            $con->query("INSERT INTO login (`status`) VALUES({$val})");
        }
    

    /functions/verifyUser.php

    <?php
    function verifyUser($con,$username,$password)
        {
            $stmt = $con->prepare("SELECT `password`,`name` FROM login WHERE username = ? LIMIT 1");
            $stmt->execute(array($username));
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            if(empty($result['password']))
                return false;
    
            $isValid = password_verify($password, $result['password']);
            return ($isValid)? $result['name'] : false;
        }
    

    /config.php

    <?php
    # Create some helpful constants
    define('DS',DIRECTORY_SEPARATOR);
    define('ROOT_DIR',__DIR__);
    define('FUNCTIONS',ROOT_DIR.DS.'functions');
    # Start session
    session_start();
    # Start database
    require_once(ROOT_DIR.DS."condb.php");
    

    /whatever.php

    <?php
    # Add config at top
    require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
    # Add our functions to be used
    require_once(FUNCTIONS.DS.'suggestEatingProblem.php');
    require_once(FUNCTIONS.DS.'addLoginStatus.php');
    # If no session, redirect
    if (!isset($_SESSION['user'])) {
        header("Location: index.php");
        # Make sure to stop your script if you are done with the page
        exit;
    }
    # Check if submission
    if(isset($_POST['BTN_P2'])) {
        # Assign problem (trim it)
        $_SESSION['problem'] = trim($_POST['problem']);
        # If yes
        if($_SESSION['problem'] == "yes") {
            # Redirect and stop the script execution
            header("Location: survey_3.php");
            exit;
        }
        else {
            # Just do one "try" here...
            try {
                # Run your function here
                suggestEatingProblem($cn,array(
                    $_SESSION['time'],
                    $_SESSION['suggest'],
                    $_SESSION['phone'],
                    $_SESSION['eat'],
                    $_SESSION['problem']
                ));
                # Run your second function here
                addLoginStatus($cn,'0');
                # Redirect. You can not put content before you redirect, so
                # remove the "Finished" echo
                header('Location: finish.php');
                exit;
            } 
            catch (PDOException $e){
                echo 'Error occurred: '.$e->getTraceAsString();
            }
        }
    }
    else {
        echo 'No request sent.';
    }
    

    Validation portion:

    # Add function (see the other example to add the config)
    require_once(FUNCTIONS.DS.'verifyUser.php');
    # If there is a submission
    if(isset($_POST['BTN_ENTER'])) {
        try {
            # Fetch the name (or false)
            $user = verifyUser($cn,trim($_POST['username']),trim($_POST['password']));
            # If not false
            if($user) {
                # Assign the value
                $_SESSION['user'] = $user;
                # Redirect and stop execution of script
                header('Location: survey.php');
                exit;
            }
        }
        catch(PDOException $d) {
            echo $e->getMessage();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输