Toni Reese Toni Reese - 6 months ago 16
HTML Question

How to send input values along with select option to php

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

Answer

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>