I am trying to insert multiple values from the select drop down using PHP, but it's only taking the last value selected

how to save multiple dropdownlist selected value in php
how to display multiple selected value of dropdownlist in php
insert multiple select value using php and mysql
how to insert dropdown selected value in database in php
how to insert multiple select values in database in codeigniter
how to insert select option value in database using php
php mysql drop down menu to select data to display example
multiple selection in dropdown in php and mysql

I have tried using the implode and foreach function, but still it's taking the last selected value.

This is the php insertion code

<?php

if (isset($_POST['register'])) {

    $research = $_POST['research'];
    $reg = $_POST['RegNo'];
    $topic = $_POST['topic'];
    $year = $_POST['year'];
    $staff = $_POST['staff'];

    foreach ($staff as $choice) {
        require 'connectdb.php';
        $statement = $conn->prepare('INSERT INTO research ( Name, Topic, Year, RegNo, staffID) VALUES (?,?,?,?,?);');
        $statement->bind_param('sssss', $researchh, $topicc, $yearr, $regg, $stafff);
        $researchh = $research;
        $topicc = $topic;
        $yearr = $year;
        $regg = $reg;
        $stafff = $choice;
    }

    if ($statement->execute() == false) {
        if ($conn->errno === 1062) {
            header('Location:?exists');
        }
    } else {
        header('Location:?newstudentTopic');
    }

}
?>

This is the form field:

<div class="col-md-6">

    <label for="gender">Supervior</label>
    <select class="form-control selectpicker border border-info" id="staff" required name="staff[]"
            data-live-search="true" multiple data-max-options="2" multiple="multiple">

        <option value=""> Allocate Supervisor</option>

        <?php
        require 'connectdb.php';
        $statement = $conn->prepare('SELECT staffid,fname,lname from staff');
        $statement->execute();
        $statement->bind_result($staffid, $fname, $lname);
        $statement->store_result();
        while ($statement->fetch()) {
            ?>
            <option value="<?php echo $staffid ?>"><?php echo $fname . ' ' . $lname ?></option>
            <?php
        }
        $statement->close();
        $conn->close();
        ?>
    </select>

</div>

The execute command is outside the loop, also do not include the 'connectdb.php' inside the loop or use require_once.

Inserting data to database from multiple select list using php an mysql, I have a form with many multiple select lists,How can i submit the multiple In the first query, you're inserting two values into each table row, but in the see in my head how you would relate the two values in separate drop-downs. Try it. Write the code above without the typos, insert some data from your  In Multiple Select dropdown, we are getting value in list form, the value of this multiple select dropdown can be get by. PHP. if(isset($_POST['state_id']))$state_id=implode(',',$_POST['state_id']); 1. 2. if(isset($_POST['state_id'])) $state_id=implode(',',$_POST['state_id']);

You ought to prepare the sql once and then execute multiple times ~ that's part of the beauty of the prepared statement style.

You ought to test that the required fields are available within the POST array - below I created an array of fields to test ~ the first test determines if any of the required fields are empty and the second determines if someone is trying to inject other parameters in to the POST array.

You should include require the database connection ONCE and not within the loop.

Finally just loop through the array of staff and execute the query for each iteration.

<?php 
    try{
        $results=[];
        $fields=['research','RegNo','topic','year','staff','register'];

        foreach( $fields as $field ) {
            if( empty( $_POST[ $field ] ) ) {
                throw new Exception( sprintf( 'Missing field "%s"', $field ) );
            }
        }

        foreach( $_POST as $field ){
            if( !in_array( $field, $fields ) ) {
                throw new Exception( sprintf('Unknown field "%s"', $field ) );
            }
        }
        /* include the db connection once, NOT in the loop */
        require 'connectdb.php';

        $research=$_POST['research'];
        $reg=$_POST['RegNo'];
        $topic=$_POST['topic'];
        $year=$_POST['year'];
        /* this is a multiple field - array */
        $arr_staff=$_POST['staff'];

        /* Create the sql statement once - NOT in the loop */
        $sql='INSERT INTO research ( `Name`, `Topic`, `Year`, `RegNo`, `staffID`) VALUES (?,?,?,?,?);'
        $stmt=$conn->prepare( $sql );

        if( !$stmt )throw new Exception('Failed to prepare SQL');
        $stmt->bind_param('sssss', $research, $topic, $year, $reg, $staff );


        foreach( $arr_staff as $staff ){
            $results[]=$stmt->execute();
        }

        exit( header( 'Location: ?newstudentTopic' ) );

    } catch( Exception $e ){
        exit( $e->getMessage() );
    }
?>

Handling select box (drop-down list) in a PHP form, This tutorial will show you how to add select boxes and multi-select boxes to a form, selects “Male”, the “formGender” value when accessed by PHP will be “M​”. user could monkey around with the form and submit whatever value he wants​. How to store/submit drop down list selected item to phpmyadmin MySQL db using PHP script code. In this tutorial we are simply creating an html from with select name and label tags. This tags create drop down list in html.

There are multiple glitches in your code. I have optimized it a bit and fixed the issue pertaining to your needs. please let me know if it works.

I have tried using the implode and foreach function, but still it's taking the last selected value.

This is the php insertion code

<?php

if (isset($_POST['register'])) {
require 'connectdb.php';

$research = $_POST['research'];
$reg = $_POST['RegNo'];
$topic = $_POST['topic'];
$year = $_POST['year'];
$staff = $_POST['staff'];
$isSuccess = 1;
foreach ($staff as $choice) {
    $statement = $conn->prepare('INSERT INTO research ( Name, Topic, Year, RegNo, staffID) VALUES (?,?,?,?,?);');
    $statement->bind_param('sssss', $researchh, $topicc, $yearr, $regg, $stafff);
    $researchh = $research;
    $topicc = $topic;
    $yearr = $year;
    $regg = $reg;
    $stafff = $choice;
    if ($statement->execute() == false) {
       $isSuccess = 0;
    }
}


    if (!$isSuccess) {
        header('Location:?exists');
    }
    else {
    header('Location:?newstudentTopic');
    }

}
?>

Chosen multiple select checkbox, In the below example we explain you how to easily insert multiple checkbox value in I am going to show you a jQuery plugin that not only supports selecting I have already disply the data in my Dropdownlist and select them as it works. values in access 2000; Passing multiple values of a select box to another php  Inserting data to database from multiple select list using php an mysql drop-down value type - type of entry - subject / farming / whatever other field type If the other columns don’t

Place your $statement->execute() within your foreach loop and you are good to go :)

You could do it like this:

// needs to be included only once
require 'connectdb.php';

// you can use this multiple times
$statement = $conn->prepare('INSERT INTO research ( Name, Topic, Year, RegNo, staffID) VALUES (?,?,?,?,?);');

$success = true;
foreach ($staff as $choice) {
    $researchh = $research;
    $topicc = $topic;
    $yearr = $year;
    $regg = $reg;
    $stafff = $choice;

    $statement->bind_param('sssss', $researchh, $topicc, $yearr, $regg, $stafff);

    $success = $statement->execute() && $success;

    // Do this if you want to stop inserting after one fails
    // if($success === false) {
    //     break;
    // }
}

if ($success) {
    header('Location:?exists');
} else {
    header('Location:?newstudentTopic');
}
exit; // thx @halfer :)

In case you want to insert only if there is not a single execute failing have a look at transactions: http://php.net/manual/en/pdo.begintransaction.php

PHP and HTML - Manual, What encoding/decoding do I need when I pass a value through a form/URL? I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. How do I get all the results from a select multiple HTML tag? down. -1. murphy ¶. 5 months ago. The scenario: 1. There is a php script which  you are getting only 1 insert because you are setting the value of $_GET['cars'] to the last selected item in your multiple. to acheive what you are looking for set the select name of cars to cars[].

Multiple dropdown with jquery ajax and php, hii, I have a html dropdown(for selecting products)where i am fetching option values by calling an API .As a single vendor can sell multiple products  When creating a drop-down list in HTML, the select tag is used to enclose all of the options in the drop-down list. The select tag has an opening and closing tag. -The option tag is for each of the individual choices in a drop-down list that a user can select. The option tag contains the "value" attribute.

Add a new option to a select with jQuery, Adding a single option can be done by appending HTML to the select box. not work correctly in Internet Explorer; it will add the new option but only the value and not display any text. Adding multiple options I'll note this page down for a rewrite. It's always going to be tricky to work with 3rd party data you can't control,  I would like to obtain a value that is selected from a drop down box. It has entries from a database using jQuery. I would then like to add the value from the drop down box into the SQL statement to query. I tried using a submit button to get it to work but struggled. Any help would be appreciated. Here is my option box:

Multiple checkbox in asp net, In this example, four columns multi-select dropdown with checkboxes is to retrieve multiple data from mysql using php and multiple checkboxes; multiple I am trying to insert mutiple checkbox list values in my sql database in single column. That works quite nicely to extract the value that I need when the form input box has only a single value . I am now trying to do the same thing when using a select drop down form with multiple

Comments
  • Also, the header() Location statements should be immediately followed by an exit, so the script does not attempt to carry on afterwards.