0

Problem

So, the user has to input a team's leader_id, and the user can input up to 6 student_id. My problem is that the data isn't being inserted into the database. The problem is under the comment PROBLEM.

So I first get the users input data, and I store the leader_id inside a separate variable and the student_id's inside an array. Next, I loop through the student_id and check if the user did not input anything in the student_id field, then insert the leader_id. But if the user did input 1 or more student_id's , then I looped trough the array and stored the inputs that had a value in them. Then I inserted the data into the database.

Teams Database (EMPTY)

team_id | leader_id | student_id

PHP Code

<?php 

error_reporting(0);
require '../../connect.php';

$leader_id = $_POST['leader_id'];
$students = array(
    $_POST['student_id_1'],
    $_POST['student_id_2'],
    $_POST['student_id_3'],
    $_POST['student_id_4'],
    $_POST['student_id_5'],
    $_POST['student_id_6'],
);

$student_save = array();

if(!empty($leader_id)) {

    foreach ($students as $student) {

        if(isset($student)) {
            array_push($student_save, $student);
        } else {
            $insert = mysqli_query($link, "INSERT INTO teams (leader_id) VALUES ('$leader_id')");

            header("Location: ../../../admin.php?message=Success!");

            break;
        }

    }

    foreach ($student_save as $student) {
        // PROBLEM
        $insert = mysqli_query($link, "INSERT INTO teams ($leader_id, $student_id) VALUES ($leader_id, $student)");

        if($insert) {
            header("Location: ../../../admin.php?message=Sorry we ran into an error");
        } else {
            header("Location: ../../../admin.php?message=Success!");
        }
    }

} else if(empty($leader_id)){
    header("Location: ../../../admin.php?message=There must be a leader");
}

?>

If you have any question, please ask me.

3
  • See how to get useful error messages in PHP and use mysqli_error($link); to get MySQL errors. Without the concrete errors, we can guess, but I don't like guesswork - I like facts ;-) Commented Apr 3, 2017 at 23:48
  • 2
    You are wide open to SQL injection. Learn how to use prepared statements and parameterized queries or someone will hack your database. Commented Apr 3, 2017 at 23:57
  • 1
    And the column names in your second INSERT statement have dollar signs in them. Commented Apr 4, 2017 at 0:03

1 Answer 1

1

The problem was this:

$insert = mysqli_query($link, "INSERT INTO teams ($leader_id, $student_id) VALUES ($leader_id, $student)");

There was a dollar sign in the INSERT

It should've been:

$insert = mysqli_query($link, "INSERT INTO teams (leader_id, student_id) VALUES ($leader_id, $student)");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.