如何从数据库中获取数据并将其存储在会话PHP中

时间:2016-06-17 00:21:55

标签: php mysql session

我想参加托福考试。当用户想要开始测试时,第一个用户必须输入电子邮件。因此,当用户单击开始时,用户具有id。我想从桌子上拿出id' id'并将其保存在会话中。所以,当我想从“倾听”,“结构”和“结构”中获取分数。并且'阅读'表,我用那个id。

但问题是:当我做测试时,听力,阅读和结构分数将为' 0'。但我确定我已正确回答了问题。也许是因为id没有正确保存在会话中。请帮助meeee

的index.php

<form method="POST" action="add_id.php">
         <input type="text" name="email" placeholder="Email">
         <input name="btn" type="submit" value="Start"/>
         </form>

add_id.php

<?php 
    include "connection.php";
    $email = $_POST['email'];

    $query = "INSERT INTO id(email) VALUES ('$email')";
        if(mysql_query($query)){
         $q = "SELECT * FROM id";
         $ex=mysql_query($q);
         $id = $ex['id'];
         session_start();
         $_SESSION['id'] = $id;

        header("location:test_structure.php");
        }

        else {
        echo mysql_error();
    }
?>

calculate.php

<?
include "connection.php";
$id   =$_SESSION['id'];

              $query ="SELECT * FROM Reading WHERE Reading.id='$id'";
              $ex=mysql_query($query);
              $data=mysql_fetch_array($ex);
              $right_structure = $data['rightanswer_read'];
              $Reading = $data['score_read'];

              $query ="SELECT * FROM Structure WHERE Structure.id='$id'";
              $ex=mysql_query($query);
              $data=mysql_fetch_array($ex);
              $right_structure = $data['rightanswer_struct'];
              $Structure = $data['score_struct'];

              $q ="SELECT * FROM Listening WHERE Listening.id='$id'";
              $e=mysql_query($q);
              $d=mysql_fetch_array($e);
              $right_listening = $d['rightanswer_list'];
              $Listening = $d['score_list'];

              $final_score = (($Listening + $Structure + $Reading)/3) * 10; 

              $NA = "INSERT INTO final_score VALUES ('$email', '$final_score', '$Listening', '$Structure', '$Reading', '$right_listening', '$right_structure', '$right_reading')";
              if(mysql_query($NA)){
                   header("location:index.php");
              }else {
                    echo mysql_error();
              }

              }
              ?>

这是id表格结构:

CREATE TABLE IF NOT EXISTS `id` (
`id` int(100) NOT NULL,
  `email` varchar(30) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

1 个答案:

答案 0 :(得分:0)

像这样更改您的add_id.php文件,

<?php
    session_start();
    include "connection.php";
    $email = $_POST['email'];

    $query = "INSERT INTO id(email) VALUES ('$email')";
    if(mysql_query($query)){
         $id = mysql_insert_id();
         $_SESSION['id'] = $id;

        header("location:test_structure.php");
    }
    else {
        echo mysql_error();
    }
?>

另请阅读http://php.net/manual/en/function.mysql-insert-id.php

处的功能mysql_insert_id()