使用foreach循环后,数据不会插入数据库

时间:2018-05-24 19:38:42

标签: php mysql foreach

我需要插入2个选项($choices)和2个类别($categories),这些选项与Question_ID最后插入的问题相关联。问题插入正常。但是,选择和类别不是。这些数组都包含所需的所有数据。我需要将每个选项与其相关的类别ID同时插入,因为在网站的另一个点需要这些选项,并且每个选项必须与特定的Category_ID相关。

UPDATE - 我在内部foreach循环中添加了一个if语句,如果语句执行将继续循环,如果它没有,那么错误将被回显。这个错误得到了回应。我该如何解决这个问题?

PHP代码:

<?php
session_start();
include_once 'DBConnection.php';

if(isset ($_POST['Question']) && isset($_POST['Category_ID1']) && isset($_POST['Category_ID2']) && isset($_POST['Choice1']) && isset($_POST['Choice2'])) {
//get post variable
$question = $_POST['Question'];
//category array
$categories = array();
$categories[0] = $_POST['Category_ID1'];
$categories[1] = $_POST['Category_ID2'];
//Choices array
$choices = array();
$choices[0] = $_POST['Choice1'];
$choices[1] = $_POST['Choice2'];

//Insert question query
$stmt = mysqli_prepare($conn, "INSERT INTO Questions (Question) VALUES ('?')");
mysqli_stmt_bind_param($stmt, 's',$question_p);
$question_p = $question;
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_num_rows($stmt);
$id = mysqli_insert_id($conn);

if ($result) {
    foreach ($choices as $choice) {
        if ($choice != '') {
            //Choice query
            foreach ($categories as $category) {
                if ($category != '') {
                    $query = "INSERT INTO Choices(Choice, Question_ID, Category_ID) VALUES ('$choice', '$id', '$category')";
                    $results = $conn->query($query);
                    if($results){
                        continue;
                    }else{
                        echo "error";
                    }
                }
            }
        }
    }
} else {
    echo $conn->error;
}
}else{
echo "Not Set";
}

2 个答案:

答案 0 :(得分:0)

尝试添加else部分以捕捉潜在错误:

else
{
    echo $conn->error;
}

您也不应该直接在SQL语句中使用用户输入。使用预准备语句来保护您的站点免受SQL注入。

答案 1 :(得分:0)

使用预准备语句,PDO将提高安全性并使代码更有效。

所以尝试这样的事情:

//.... 
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);

$sql = "INSERT INTO Questions (Question) VALUES (:question)";

try{
    //prepare your first query
    $stmt = $pdo->prepare($sql);

    //now you can bind your parameters to the query
    $stmt->bindParam(':question', $question, PDO::PARAM_STR);

    $stmt->execute();
    $id = $pdo->lastInsertId();

    // check id instead -- result can be true even if the row wasn't inserted
    if ($id > 0) {
        // define your next query only once!
        $query = "INSERT INTO Choices(Choice, Question_ID, Category_ID) VALUES (:choice, :id, :category)";

        //prepare only once!
        $stmtQuery = $pdo->prepare($query);

        //bind only once!
        $stmtQuery->bindParam(':choice', $choice, PDO::PARAM_STR);
        $stmtQuery->bindParam(':id', $id, PDO::PARAM_INT); //assuming id is type int
        $stmtQuery->bindParam(':category', $category, PDO::PARAM_STR);

        foreach ($choices as $choice) {
            if ($choice != '') {
                //Choice query
                foreach ($categories as $category) {
                    if ($category != '') {
                        //execute as often as needed
                        $stmt->execute();
                    }
                }
            }
        }
    }
    else {
        echo = "no row inserted";
    }
}
catch (PDOException $e){
    echo = "An error occurred." . $e->getMessage();
}

<强>声明

我只是在标准文本编辑器中输入了它。所以我希望我没有犯过太多错误,请保持警惕。

编辑

使用依赖项插入函数(仅在先前的插入成功时才需要插入新的数据行),您应该包含最适合的“beginTransaction / commit / rollback”策略。在$pdo->beginTransaction();开始时使用$pdo->rollback();,您希望在发生错误时回滚,$pdo->commit();您准备好将所有更改设为“永久”。