【问题标题】:Save or store data in a database from program从程序将数据保存或存储在数据库中
【发布时间】:2019-01-17 22:36:02
【问题描述】:

我正在编写一个用户必须注册才能执行一些练习的代码。每个练习都有一个'id',用户可以选择练习的难度级别。

我想将'exercise_id''user_id''difficulty' 保存在数据库表中。到目前为止,我已经设法将'exercise_id''difficulty' 保存在一个名为'answers' 的表中,但我无法保存'user_id'

在选择练习和难度级别之前,用户必须使用他们的用户名注册,每次注册时,'user_id' 就会创建并增加(我已设法将其保存在'users' 表中)。我想做的是保存当前记录在表'answers' 中的'user_id'。 这就是我目前所拥有的......你能帮帮我吗?

当用户按下submit时,我试图获取从表'users'记录的'user_id'并将其存储在表'answers'中

这是文件:ChooseExercise.php

<?php
// Start the session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";

$conn = new mysqli($servername, $username, $password, $dbname);
/*echo*/ $id=$_GET['id'];
$sql = "SELECT * FROM exercises where exercise_id='$id'";
$result = $conn->query($sql); /*Check connection*/
?>

<div id="centered_B" class="header">

<?php
$row = $result->fetch_assoc();
    echo '<h1>' . $row["exercise_id"]. ". " . $row["title"] . '</h1>' . "<br>" . '<p>' . $row["text"] . '</p> <img width="603" height="auto" src="' . $row["image_path"] . '"><br><br>


    <input type="radio" name="choice" value= "1" /><img src="' . $row["image_path_A"] . '"/><br>
    <input type="radio" name="choice" value= "2" /><img src="' . $row["image_path_B"] . '"><br>
    <input type="radio" name="choice" value= "3" /><img src="' . $row["image_path_C"] . '"><br>';


/*var_dump($id)*/
?>

    <br><br><br><!--- Select difficulty --->

    <p2>Select difficulty level:</p2>

    <form action='' method='post'>
    <select name="choose" id="choose">>
        <option value="1" <?php if($row["difficulty"]=="1") { echo "selected"; } ?> >1</option>
        <option value="2" <?php if($row["difficulty"]=="2") { echo "selected"; } ?> >2</option>
        <option value="3" <?php if($row["difficulty"]=="3") { echo "selected"; } ?> >3</option>
        <option value="4" <?php if($row["difficulty"]=="4") { echo "selected"; } ?> >4</option>
        <option value="5" <?php if($row["difficulty"]=="5") { echo "selected"; } ?> >5</option>
    </select>

    <br><br><br><!--- Button --->

<!--        <button class="buttonSubmit" >Submit</button>-->
        <input type="submit" name="submit" value="Submit">
        <button class="buttonNext" >Next Question</button>
    </form>

</div><!--- end of centered_B div --->



<?php

if (isset($_POST['submit'])) {
    $user_id = $_SESSION['user_id']; /*ERROR: Notice: Undefined index: user_id */
   $user_check_query = "SELECT * FROM users WHERE id='$user_id'";


    if(isset($_POST['choose'])){
        $difficulty=$_POST['choose'];
//      */$user_id = $_SESSION['user_id'];*/
        $query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student) VALUES ('$id','$user_id', '$difficulty')";
        $sql=mysqli_query($conn,$query);

    }
}

?>

<div id="centered_C" class="header">
    <!--- Solution --->

        <button onclick="solutionFunction()" class="button_Solution" >Solution</button>



    <div id="solution" style="display: none;">

        <img src="<?php echo $row["solution_path"]; ?>" >

    </div>


</div><!--- end of centered_C div --->

<!--------- Solution -------------->
<script>
    function solutionFunction() {
        var x = document.getElementById("solution");
        if (x.style.display === "none") {
            x.style.display = "block";
        } else {
            x.style.display = "none";
        }
    }
</script>

这是文件:server.php

<!--Mysql DataBase-->

<?php
session_start();

// initializing variables
$username = "";
$email    = "";
$errors = array();

/*Connect with the DB*/
$servername = "localhost";
$username = "";
$password = "";
$dbname = "project";

$db = new mysqli($servername, "root", $password, $dbname);


// REGISTER USER
if (isset($_POST['reg_user'])) {
    // receive all input values from the form
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $email = mysqli_real_escape_string($db, $_POST['email']);
    $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
    $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

    // form validation: ensure that the form is correctly filled ...
    // by adding (array_push()) corresponding error unto $errors array
    if (empty($username)) { array_push($errors, "Username is required"); }
    if (empty($email)) { array_push($errors, "Email is required"); }
    if (empty($password_1)) { array_push($errors, "Password is required"); }
    if ($password_1 != $password_2) {
        array_push($errors, "The two passwords do not match");
    }

    // first check the database to make sure
    // a user does not already exist with the same username and/or email
    $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
    $result = mysqli_query($db, $user_check_query);
    $user = mysqli_fetch_assoc($result);

    if ($user) { // if user exists
        if ($user['username'] === $username) {
            array_push($errors, "Username already exists");
        }

        if ($user['email'] === $email) {
            array_push($errors, "email already exists");
        }
    }

    // Finally, register user if there are no errors in the form
    if (count($errors) == 0) {
        $password = md5($password_1);//encrypt the password before saving in the database

        $query = "INSERT INTO users (username, email, password) 
              VALUES('$username', '$email', '$password')";
        mysqli_query($db, $query);
        $_SESSION['username'] = $username;
$_SESSION['user_id'] = mysqli_insert_id($db);
var_dump(mysqli_insert_id($db));
        header('location: index.php');
    }
}

// ...
// check if the user has filled the form correctly

// LOGIN USER
if (isset($_POST['login_user'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);

    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }

    if (count($errors) == 0) {
        $password = MD5($password); /*security reasons*/
        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($db, $query);
        if (mysqli_num_rows($results) == 1) {
            $_SESSION['username'] = $username;
            $_SESSION['user_id'] = $results->fetch_object()->id; //returns id from last query /*StackO*/
            header('location: index.php');
        }else {
            array_push($errors, "Wrong username/password combination");
        }
    }
var_dump($results->fetch_object()->id);
}

?>

数据库表

CREATE TABLE answers(
    exercise_id_fk INT,
    student_id INT,
    difficulty_student INT,
    FOREIGN KEY(exercise_id_fk) REFERENCES exercises(exercise_id)
);


CREATE TABLE users (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username varchar(100) NOT NULL,  
)

【问题讨论】:

    标签: php mysql database store


    【解决方案1】:

    编辑:更新问题

    在注册和登录之前header('location: index.php');

    1) 在 REGISTER USER 上,将用户 ID 保存在 SESSION 中:

    // Finally, register user if there are no errors in the form
    if (count($errors) == 0) {
    
        $query = "INSERT INTO users (username) VALUES('$username')";
        mysqli_query($db, $query);
        $_SESSION['username'] = $username;
        $_SESSION['user_id'] = mysqli_insert_id($db); //returns id from last query
    
        header('location: index.php');
    }
    

    }

    2) 在 LOGIN USER 上,执行相同操作,但从数据库中检索:

    if (count($errors) == 0) {
        $password = MD5($password); /*security reasons*/
        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($db, $query);
        if (mysqli_num_rows($results) == 1) {
            $_SESSION['username'] = $username;
            $_SESSION['user_id'] = $results->fetch_object()->id;
            header('location: index.php');
        }else {
            array_push($errors, "Wrong username/password combination");
        }
    }
    

    【讨论】:

    • 好吧,我照你说的做了,但我有以下错误:忽略错误抑制。你觉得是什么?
    • 我还将数据存储在 2 个不同的 php 文件中的表中,你认为是因为这个吗?
    • @ana 忽略错误抑制?为了什么?这是完整的错误吗?
    • 对不起,错误是:SCREAM: Error suppression ignored for Notice: Undefined variable: user_id and Notice: Undefined variable: _SESSION
    • @ana 这到底发生在哪里?可能在您的 var_dump($user_id) 上,因为它从来没有被定义过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多