php—从程序将数据保存或存储到数据库中

hjzp0vay  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(426)

我正在编写一个代码,用户必须注册才能执行一些练习。每个练习都有一个 'id' 用户可以选择练习的难度。
我想保存 'exercise_id' , 'user_id' 以及 'difficulty' 在数据库的表中。到目前为止,我已经设法保存在一个名为 'answers' 这个 'exercise_id' 以及 'difficulty' ,但我无法挽救 'user_id' .
在选择练习和难度等级之前,用户必须用用户名注册,每次注册时 'user_id' 正在创建和增加(我已设法保存在 'users' 表)。我想做的是保存 'user_id' 当前记录在表中的 'answers' . 这就是我目前所拥有的。。。你能帮我吗?
我正试着去拿 user_id '从表中记录的' users '并将其存储在表中' answers '当用户按下 submit 这是文件: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,  
)
jum4pzuy

jum4pzuy1#

编辑:更新问题
之前 header('location: index.php'); 在注册和登录时:
1) 在注册用户时,将用户id保存在会话中:

// 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) 在用户登录时,执行相同的操作,但从数据库检索:

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");
    }
}

相关问题