1

I have this following codes.How do i send this form to php so in php i can access it like studentName course2 year3.Basically i have a table which looks like this studentName|course|year.I am looking for the right way to organize the data in order to insert it to my table.I have tried sending the form not as an array but i have to write 3 queries to insert 3 inputs.Is there any way to loop through the data and insert?

    <form id="myform" method="POST">
    <label>college:</label><input type="text"  id="clg" name="clg"/><br/>
    <label>Student:-</label><input type="text" name="name[]" id="name" />
    <select name="taskOpen[]">
    <option value="1">course1</option>
    <option value="2">course2</option>
    <option value="3">course3</option>
    <option value="4">course4</option>
    </select>
    <select name="year[]">
    <option value="1">year1</option>
    <option value="2">year2</option>
    <option value="3">year3</option>
    <option value="4">year4</option>
    </select>
 <label>Student:-</label><input type="text" name="name[]" id="name" />
    <select name="taskOpen[]">
    <option value="1">course1</option>
    <option value="2">course2</option>
    <option value="3">course3</option>
    <option value="4">course4</option>
    </select>
    <select name="year[]">
    <option value="1">year1</option>
    <option value="2">year2</option>
    <option value="3">year3</option>
    <option value="4">year4</option>
    </select>
    <input type="button" value="search"  id="btn"/>
    </form>

Here is what i have in php--

if(isset($_POST['name']) && isset($_POST['taskOpen'])
&& isset($_POST(['year'])){
$name=$_POST['name'],$course=$_POST['taskOpen'],$year=$_POST['year']
}
else {
echo "something";
}
foreach($name as $student){
$sql=$conn->prepare("INSERT INTO `student`(`studentName`) VALUES(:s_n)");
$sql->execute(array(":s_n"=>$student));
}
foreach($course as $courseN){
$sql=$conn->prepare("INSERT INTO `student`(`course`) VALUES(:co)");
$sql->execute(array(":co"=>$courseN));
}
foreach($year as $yearD){
$sql=$conn->prepare("INSERT INTO `student`(`year`) VALUES(:ya)");
$sql->execute(array(":ya"=>$yearD));
}
5
  • lets see what you have on the PHP side, so we can help you adjust it. Commented May 13, 2016 at 19:58
  • Start by changing <input type="button" value="search" id="btn"/> to <input type="submit" name="submit" value="search">, so you can submit the form. Then analyze the post content with print_r($_POST). Commented May 13, 2016 at 20:00
  • @PedroLobito i am sending the form using ajax .and i can print that in php Commented May 13, 2016 at 20:12
  • @cmorrissey i have added my php . Commented May 13, 2016 at 20:19
  • @ToniReese while your insert is incorrect may I applaud you for your correct usage of prepared statements yea! seriously good job, usually you will see code that's out dated and susceptible to SQL injections. Commented May 13, 2016 at 20:46

2 Answers 2

1

Here is what i think you are going for...

HTML

    <!-- THE NAMES OF INPUT ELEMENTS WRAPPED IN A college_data-->
    <form id="myform" method="POST">
        <label>college:</label><input type="text" id="clg" name="college_data[clg]"/><br/>
        <label>Student:-</label><input type="text" name="college_data[name]" id="name"/>
        <select name="college_data[taskOpen1]">
            <option value="1">course1</option>
            <option value="2">course2</option>
            <option value="3">course3</option>
            <option value="4">course4</option>
        </select>

        <select name="college_data[year1]">
            <option value="1">year1</option>
            <option value="2">year2</option>
            <option value="3">year3</option>
            <option value="4">year4</option>
        </select>

        <label>Student:-</label><input type="text" name="name[]" id="name"/>
        <select name="college_data[taskOpen2]">
            <option value="1">course1</option>
            <option value="2">course2</option>
            <option value="3">course3</option>
            <option value="4">course4</option>
        </select>

        <select name="college_data[year2]">
            <option value="1">year1</option>
            <option value="2">year2</option>
            <option value="3">year3</option>
            <option value="4">year4</option>
        </select>
        <input type="submit" value="search" id="btn"/>
    </form>

PHP

    <?php

        $college        = isset($_POST['college_data']['clg'])          ? htmlspecialchars(trim($_POST['college_data']['clg']))         :null;
        $studentName    = isset($_POST['college_data']['name'])         ? htmlspecialchars(trim($_POST['college_data']['name']))        :null;
        $studentName2   = isset($_POST['college_data']['name2'])        ? htmlspecialchars(trim($_POST['college_data']['name2']))       :null;
        $taskOpen1      = isset($_POST['college_data']['taskOpen1'])    ? htmlspecialchars(trim($_POST['college_data']['taskOpen1']))   :null;
        $taskOpen2      = isset($_POST['college_data']['taskOpen2'])    ? htmlspecialchars(trim($_POST['college_data']['taskOpen2']))   :null;
        $year1          = isset($_POST['college_data']['year1'])        ? htmlspecialchars(trim($_POST['college_data']['year1']))       :null;
        $year2          = isset($_POST['college_data']['year2'])        ? htmlspecialchars(trim($_POST['college_data']['year2']))       :null;


        // TEST::: DELETE EVERYTHING BELOW THIS LINE ONCE YOU ARE DONE CONFIRMING THAT IT IS OK  
        // CLICK THE SUBMIT BUTTON TO SEE THE VALUES REFLECTED HERE AS SOON AS THE FORM GETS SUBMITTED...           
        var_dump($college);
        var_dump($studentName);
        var_dump($studentName2);
        var_dump($taskOpen1);
        var_dump($taskOpen2);
        var_dump($year1);
        var_dump($year2);
    ?>

VALIDATION

    <?php

        // FIRST CREATE AN ARRAY TO HOLD MESSAGES TO BE SHOWN TO THE USER
        // SHOULD ANYTHING GO WRONG... & ALSO AN EMPTY ERROR MESSAGE STRING...
        $arrErrorBag  = array();
        $strErrorMsg  = "";

        if(isset($_POST['submit'])) {
            // LET'S ASSUME FOR THE MOMENT YOU HAVE SPECIAL CONSTRAINTS
            // TO BE APPLIED TO EACH FIELD DURING YOUR VALIDATION PROCESS.
            // WE WILL USE SIMPLE REGULAR EXPRESSIONS HERE FOR DEMONSTRATION

            // BUILD VALIDATION REG-EXES FOR THE FIELD:: WE WANT ONLY A MINIMUM OF 10 CHARACTERS FOR STUDENT & COLLEGE
            // AGAIN; YOU CAN GO WILD BUT WE ARE KEEPING IT SIMPLE
            // PLUS, DOING IT LIKE THIS IS JUST SO THAT YOU GET THE DRIFT... ;-)
            $rxColStudent = "#(.){10,}#si";

            // FOR THE SELECTS, WE KNOW THAT THE VALUES ARE NUMBERS
            // WHICH ARE BETWEEN 1 & 4; BUT WE TAKE IT TO "BETWEEN 1 & 9"
            // AND WE INTEND USING ONE REGEX FOR ALL OF THEM SINCE THEY ARE SIMILAR.
            $rxCourseYear = "#\d#";

            // NOW WE HAVE THE REGEXES: THEN WHAT?
            // VALIDATION BEGINS... ;-)


            // TO MAKE IT EASIER ON OURSELVES, WE BUNDLE ALL THE STUDENT, STUDENT1 & COLLEGE FIELDS
            // INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
            // VALIDATE COLLEGE, STUDENT & STUDENT2...
            $arrStringValFields = array(
                "student"   => array("Student Nr. 1",   $studentName),
                "student2"  => array("Student Nr. 2 ",  $studentName2),
                "college"   => array("College",         $college),
            );

            // RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
            foreach ($arrStringValFields as $fieldName => $arrErrStringVal) {
                if (!preg_match($rxColStudent, $arrErrStringVal[1])) {
                    $arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to have a minimum of 10 Characters. Please, check that you have not missed something.";
                }
            }

            // TO MAKE IT AGAIN EASIER ON OURSELVES, WE BUNDLE ALL OTHER FIELDS THAT HAVE NUMERIC VALUES
            // INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
            $arrNumericFields = array(
                "taskOpen1" => array("Open Task Nr. 1",        $taskOpen1),
                "taskOpen2" => array("Open Task Nr. 2 ",       $taskOpen2),
                "year1"     => array("College Year Section 1", $year1),
                "year2"     => array("College Year Section 2", $year2),
            );

            // RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
            foreach ($arrNumericFields as $fieldName => $arrErrStringVal) {
                if (!preg_match($rxCourseYear, $arrErrStringVal[1])) {
                    $arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to be a Single Digit & it should. Did you try to *NUKE OUR ASSES OFF*. Please, don't. We are your Brothers ;-)";
                }
            }

            // MAMA MIA!!! SO MUCH FOR A SIMPLE 6-FIELD VALIDATION...
            // HAPPILY ENOUGH; WE ARE THERE... ONLY; NOT JUST YET...

            // CHECK THE ERROR BAG TO SEE IF IT CONTAINS ANYTHING.
            // IF IT DOES; THEN WE HAVE TO FIND A WAY TO DISPLAY THIS TO THE END-USER.
            if (!empty($arrErrorBag)) {
                // TURN THE ERROR BAG ARRAY TO A STRING & ASSIGN IT BACK TO THE ERROR MESSAGE STRING FOR DISPLAY...
                $strErrorMsg = "<span class='has-error'>" . implode("</span><br /><span class='has-error'>", $arrErrorBag);
            }
            else {
                // WE HAVE REACHED THE CLIMAX OF OUR POLICE-WORK...
                // SO WE EITHER STORE THE DATA TO THE DATABASE TABLE OR
                // WE BAKE & CAKE IT FOR CHRISTMAS - YOUR CALL ;-)
            }
        }

    ?>   

Now, that's OK. But how does the User get to know that there were Errors and how does s/he avoid typing-in the same information over again?

Our HTML File should have been built earlier to take that into consideration, but then again, EINTEIN WAS RIGHT!!! Human Stupidity is totally as Infinite as the Universe... but that's why we are here, right? To cut down the infinitude of our Stupidity and grow into real Humans;-) So we revise our HTML to take these into account.

HTML - REVISED: UNLEASH THE DRAGON!!!

    <!-- WE ADD A SLOT FOR OUR ERROR MESSAGE: JUST BEFORE THE FORM. -->
    <div class="error-slot"><?php echo $strErrorMsg; ?></div>
    <form id="myform" method="POST">
        <label>college:</label><input type="text" id="clg" name="college_data[clg]" value="<?php echo $college; ?>" /><br/>
        <label>Student:-</label><input type="text" name="college_data[name]"  value="<?php echo $studentName; ?>" id="name"/>
        <select name="college_data[taskOpen1]">
            <option value="1" <?php if($taskOpen1=="1"){echo "selected";} ?>>course1</option>
            <option value="2" <?php if($taskOpen1=="2"){echo "selected";} ?>>course2</option>
            <option value="3" <?php if($taskOpen1=="3"){echo "selected";} ?>>course3</option>
            <option value="4" <?php if($taskOpen1=="4"){echo "selected";} ?>>course4</option>
        </select>

        <select name="college_data[year1]">
            <option value="1" <?php if($year1=="1"){echo "selected";} ?>>year1</option>
            <option value="2" <?php if($year1=="2"){echo "selected";} ?>>year2</option>
            <option value="3" <?php if($year1=="3"){echo "selected";} ?>>year3</option>
            <option value="4" <?php if($year1=="4"){echo "selected";} ?>>year4</option>
        </select>

        <label>Student:-</label><input type="text" name="college_data[name2]"  value="<?php echo $studentName2; ?>" id="name"/>
        <select name="college_data[taskOpen2]">
            <option value="1" <?php if($taskOpen2=="1"){echo "selected";} ?>>course1</option>
            <option value="2" <?php if($taskOpen2=="2"){echo "selected";} ?>>course2</option>
            <option value="3" <?php if($taskOpen2=="3"){echo "selected";} ?>>course3</option>
            <option value="4" <?php if($taskOpen2=="4"){echo "selected";} ?>>course4</option>
        </select>

        <select name="college_data[year2]">
            <option value="1" <?php if($year2=="1"){echo "selected";} ?>>year1</option>
            <option value="2" <?php if($year2=="2"){echo "selected";} ?>>year2</option>
            <option value="3" <?php if($year2=="3"){echo "selected";} ?>>year3</option>
            <option value="4" <?php if($year2=="4"){echo "selected";} ?>>year4</option>
        </select>
        <input type="submit" value="search" name="submit" id="btn"/>
    </form>
Sign up to request clarification or add additional context in comments.

6 Comments

what if the user filled out only one input ? I mean what if the second input is optional ?
@Toni Reese No Problems.... It is still optional... as long as you are not validating those optional fields and didn't add the html REQUIRED keyword to any of the fields. that is why we have all the variables like $college, $year1, $year2, etc defaulting to NULL when the user didn't fill them. You may change the NULLs to any default values you wish or even set them to empty strings like so: ""
Thanks i will try that :-)
what if i want to validate that at least one input is selected.the other one is optional ? and plus i am sending the form using jquery ajax to php.i have used var_dump but it's returning null
That's the Easier part: You already have the Data to use in your Validation... I will update the Post in a moment to reflect the validation process in a moment... However, keep in mind that validation here might be extraneous since all you have are Drop-Downs except for COLLEGE & STUDENT. Although, it may be necessary because someone can open the Web-Inspector and inject some SH*@t into one of the Options
|
1

From your table design in the database it looks like you want to insert a student, their course and the year they are taking it in. Unless you are going to validate the form so that the number of students matches the number of courses and numbers of years so you can easily loop and insert based on their indexes, i don't see how it can be easily done. Example:

$_POST = Array(
  'name' = Array ( 'Kelly', 'Tom', 'Jack' ),
  'course' = Array ( 'Course1', 'Course2', 'Course3' ),
  'year' = Array ( '2007', '2008', '2009' ),
);


for ( $i = 0; i < count($_POST['student_name']); i++ ) {
   $sql = sprintf("INSERT INTO test ( student_name, course, year ) VALUES (   %s, %s, %d )", 
      $_POST['student_name'][$i], $_POST['course'][$i], $_POST['year'][$i] 
   );
 $conn->query($sql);
}

1 Comment

I will vote up for the example that you have given. I will try to implement your example and get back to you :-)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.