我正在尝试使用PHP从选择下拉列表中插入多个值,但这仅采用了最后选择的值

时间:2019-02-02 08:24:38

标签: php

我尝试使用implode和foreach函数,但仍采用最后选择的值。

这是PHP插入代码

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

}
?>

这是表单字段:

<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>

4 个答案:

答案 0 :(得分:0)

在执行的命令是外部的回路,也不包括循环或使用require_once内的“connectdb.php”。

答案 1 :(得分:0)

您应该prepare的SQL一次,然后execute多次〜这就是prepared statement风格的美的一部分。

您应该测试POST数组中是否有必填字段-我在下面创建了一个要测试的字段数组〜第一个测试确定是否有任何必填字段为空,第二个测试确定是否有人尝试注入到POST阵列的其它参数。

您应该一次将require数据库连接包括在内,而不应包含在循环中。

最后,只需遍历staff数组并为每次迭代执行查询。

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

答案 2 :(得分:0)

您的代码中有多个小故障。我对其进行了一些优化,并修复了与您的需求有关的问题。请让我知道它是否有效。

我尝试使用implode和foreach函数,但仍采用最后选择的值。

这是PHP插入代码

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

}
?>

答案 3 :(得分:-1)

$statement->execute()放入foreach循环中,您就可以开始了:)

您可以这样做:

// 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 :)

如果您只想在没有执行失败的情况下插入,请查看事务:http://php.net/manual/en/pdo.begintransaction.php