简体   繁体   English

我正在尝试使用PDO将数据插入数据库,但是每当我尝试查询失败时,我就会在学习PDO

[英]I'm trying to insert data into database using PDO but whenever i try the query fail, i'm learning PDO

Whenever i try to insert using the below php script i get this error message An error occurred: SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty, the foreach loop is used to process multiple select values. 每当我尝试使用下面的PHP脚本插入时,都会出现以下错误消息:SQLSTATE [42000]:语法错误或访问冲突:1065查询为空,foreach循环用于处理多个选择值。

 <?php if(isset($result)) echo $result; ?> <form class="form-horizontal" action="" method="post" role="form"> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Group Name</label> <div class="col-sm-8"> <input type="text" class="form-control" name="group_name" placeholder="Group Name" id="name"> </div> </div> <div class="form-group"> <label for="number" class="col-sm-2 control-label">Registration Number</label> <div class="col-sm-8"> <input type="text" class="form-control" name="group_reg_no" placeholder="Registration Number" id="number"> </div> </div> <div class="form-group"> <label for="leader" class="col-sm-2 control-label">Group Leader Name</label> <div class="col-sm-8"> <input type="text" class="form-control" name="leader_name" placeholder="Group Leader Name" id="leader"> </div> </div> <div class="form-group"> <label for="contact" class="col-sm-2 control-label">Group Leader Contact</label> <div class="col-sm-8"> <input type="text" class="form-control" name="leader_contact" placeholder="Group Leader Contact" id="contact"> </div> </div> <?php require_once'first.php'; ?> <div class="form-group"> <label for="activity" class="col-sm-2 control-label">Group Activity</label> <div class="col-sm-3"> <select class="form-control" name="activity[]" id="activity" multiple="multiple"> <option value="">Select Activity</option> </select> </div> </div> <div class="form-group"> <label for="category" class="col-sm-2 control-label">Group Category</label> <div class="col-sm-3"> <select class="form-control" name="category" id="category" onChange="JoinedOrNot()"> <option value="">Select Category</option> <option value="Men">Men</option> <option value="Women">Women</option> <option value="Youth">Youth</option> <option value="Both">Both</option> </select> </div> </div> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Number Of Men</label> <div class="col-sm-8"> <input type='text' size='5' name="men" id="input1" value="" class='input' disabled></input> </div> </div> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Number Of Women</label> <div class="col-sm-8"> <input type='text' size='5' name="women" id="input2" value="" class='input' disabled></input> </div> </div> <div class="form-group"> <label for="total" class="col-sm-2 control-label">Total</label> <div class="col-sm-2"> <input type='text' size='5' id="input4" value="" name="total" disabled></input> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"></label> <div class="col-sm-8"> <input type="submit" value="Register a Group" name="submit" class="btn btn-block btn-danger" id="subject"/> </div> </div> </form> 

<?php
     require_once("functions/function.php"); 
     require_once("db_connection.php");
     require_once("database.php");
     if(isset($_POST['group_name'])){
         $group_name = $_POST['group_name'];
         $group_reg_no = $_POST['group_reg_no'];
         $leader_name = $_POST['leader_name'];
         $leader_contact = $_POST['leader_contact'];
         $region = $_POST['region'];
         $district = $_POST['district'];
         $division = $_POST['division'];
         $ward = $_POST['ward'];
         $village = $_POST['village'];
         $activity = $_POST['activity'];
         $category = $_POST['category'];
         $men = $_POST['men'];
         $women = $_POST['women'];
         $total = $_POST['total'];

         try{
             foreach ((array)$_POST['activity'] as $value) {
                $sqlInsert = "INSERT INTO group_details 
                                    (group_reg_no, group_name, leader_name, 
                                    leader_contact, region, district, division, 
                                    ward, village, activity, 
                                    category, men, women, 
                                    total, registred_date) 
                            VALUES (:group_reg_no, :group_name, :leader_name, 
                                    :leader_contact, :region, :district,                                        :division, 
                                    :ward, :village, :activity,
                                    :category, :men, :women, 
                                    :total, now())";

            }
            $statement = $db->prepare($sqlInsert);
            $statement->execute(array(':group_reg_no' => $group_reg_no, ':group_name' => $group_name, ':leader_name' => $leader_name, ':leader_contact' => $leader_contact, ':region' => $region, ':district' => $district, ':division' => $division, ':ward' => $ward, ':village' => $village, ':activity' => $activity, ':category' => $category, ':men' => $men, ':women' => $women, ':total' => $total));

            if($statement->rowCount() == 1){

                $result = "<p style='padding: 20px; color: green;'> Registration Successful</p>";
            }

            }catch (PDOException $ex){

                $result = "<p style='padding: 20px; color: red;'> An error occurred: ".$ex->getMessage()."</p>";
            }
     }
     ?>

You dont need to be foreach'ing at all from what I can see 从我所见,您根本不需要去学习

<?php
     require_once("functions/function.php"); 
     require_once("db_connection.php");
     require_once("database.php");
     if(isset($_POST['group_name'])){

         try{
             $sql = "INSERT INTO group_details 
                                (group_reg_no, group_name, leader_name, 
                                 leader_contact, region, district, division, 
                                 ward, village, activity, 
                                 category, men, women, 
                                 total, registred_date) 
                        VALUES (:group_reg_no, :group_name, :leader_name, 
                                :leader_contact, :region, :district,
                                :division, :ward, :village, :activity,
                                :category, :men, :women, 
                                :total, now())";

            $statement = $db->prepare($sql);

            $params = array(':group_reg_no' => $_POST['group_reg_no'], 
                            ':group_name' => $_POST['group_name'], 
                            ':leader_name' => $_POST['leader_name'],
                            ':leader_contact' => $_POST['leader_contact'], 
                            ':region' => $_POST['region'], 
                            ':district' => $_POST['district'], 
                            ':division' => $_POST['division'], 
                            ':ward' => $_POST['ward'], 
                            ':village' => $_POST['village'], 
                            ':activity' => $activity, 
                            ':category' => $_POST['category'], 
                            ':men' => $_POST['men'], 
                            ':women' => $_POST['women'], 
                            ':total' => $_POST['total'])

            foreach ( $_POST['activity'] as $activity ) {
                $params[':activity'] = $activity;

                $statement->execute();                
            } // endforeach
            $result = "<p style='padding: 20px; color: green;'> Registration Successful</p>";
        }
        catch (PDOException $ex){
            $result = "<p style='padding: 20px; color: red;'> An error occurred: ".$ex->getMessage()."</p>";
        }
     }
?>

Of course you could remove some of the code and put the $_POST values directly into the $params array if you wanted to remove some unnecessary code. 当然,如果您想删除一些不必要的代码,则可以删除一些代码,然后将$_POST值直接放入$params数组中。

You also might want to make sure all of those $_POST values isset() before doing the INSERT, or at least initialising the scalar variables each with a default value. 您可能还需要在执行INSERT或至少初始化每个带有默认值的标量变量之前确保所有这些$_POSTisset() Just to be totally safe. 为了完全安全。

So following up my comment about classes here's my simplified answer: 因此,跟随我对类的评论,这是我的简化答案:

On the page your form is on add the following: 在页面上,添加以下内容:

<?php
require_once("functions/function.php");
require_once("db_connection.php");
require_once("database.php");
require_once('class.handleit.php');

$handle = new HandleIt();

if (isset($_POST['group_name']))
{
    $handle->handleIt($_POST['group_name'], $_POST['group_reg_no'], $_POST['leader_name'], $_POST['leader_contact'], $_POST['region'], $_POST['district'], $_POST['division'],
                     $_POST['ward'], $_POST['village'], $_POST['activity'], $_POST['category'], $_POST['men'], $_POST['women'], $_POST['total']);
}
?>

To make your life easier. 使您的生活更轻松。 Make class.handleit.php and add: 制作class.handleit.php并添加:

<?php class HandleIt
{
    public function handleIt($group, $reg, $leader, $contact, $region, $district, $division, $ward, $village, $activity, $category, $men, $women, $total)
    {
        $stmt = $this->prepare("INSERT INTO `group_details`(group_reg_no, group_name, leader_name, 
                                    leader_contact, region, district, division, 
                                    ward, village, activity, 
                                    category, men, women, 
                                    total, registred_date)
                                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?, NOW())");
        $stmt->execute([$group, $reg, $leader, $contact, $region, $district, $division, $ward, $village, $activity, $category, $men, $women, $total]);

        echo "Success!";
    }

    public function fetchIt()
    {
        $stmt = "SELECT * FROM `group_details`";
        $res = $this->prepare($stmt);
        $res->execute();

        while ($row = $res)
        {
            $rows[] = $row;
        }

        return $rows;
    }
}

You'll see there are 2 classes.. Insert and fetch (the insert explains its self and the fetch is so you can run your foreach on the desired page). 您将看到2个类。插入和提取(插入说明了它的自身,提取是这样的,因此您可以在所需的页面上运行foreach)。

Here is the foreach example: 这是foreach示例:

<?php

$getForeach = $handle->fetchIt();

foreach ($getForeach as $row)
{
    echo "<div>$row->group_name</div>";
    /* and so on.. you get the idea.. */
}

?>

Bear in mind, the foreach needs to go into the page which requires your class and the class name. 请记住,foreach需要进入需要您的班级和班级名称的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM