drrw8672 2018-05-24 19:38
浏览 123

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

I need to insert 2 choices ($choices) and 2 categories ($categories), which are linked to the question that was last inserted by the Question_ID. The question inserts fine. However, the choices and categories don't. The arrays both contain the all the data that is needed. I need each choice to be inserted at the same time as their related category ID as these are needed at another point on the site and each choice must relate to a specific Category_ID.

UPDATE - I added an if statement inside the inner foreach loop which will continue the loop if the statement executes and if it doesn't then error will get echoed. The error was echoed. How can I fix this?

PHP Code:

<?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条回答 默认 最新

  • ds000001 2018-05-24 19:45
    关注

    Try adding an else section to catch potential errors:

    else
    {
        echo $conn->error;
    }
    

    You should also never use user input directly in an SQL statement. Use prepared statements to secure your site against SQL injections.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题