将多个复选框插入 MySQL (PDO)

Posted

技术标签:

【中文标题】将多个复选框插入 MySQL (PDO)【英文标题】:inserting multiple checkboxes into MySQL (PDO) 【发布时间】:2020-11-07 21:13:58 【问题描述】:

我目前正在做一个学校项目,我正在尝试上传一个食谱的“帖子”。这包括图像、标题、说明、成分以及 1 个或多个类别。 他们都插入得很好。唯一的问题是类别。即使我选择了多个复选框,它也只会插入 1 个类别。 应该将每个复选框插入到数据库中的新行中。

我的 DAO

public function insertCategory($data, $title) 
    
  if (empty($errors)) 
    $sql = "INSERT INTO `recipes_categories` (`category_id`, `recipe_id`) VALUES(:category_id,:recipe_id);";
    $stmt = $this->pdo->prepare($sql);
    $stmt->bindValue(':category_id', $data['category_id']);
    $stmt->bindValue(':recipe_id', $title['id']);
    if ($stmt->execute()) 
      return $this->selectcategoryById($this->pdo->lastInsertId());
    
  
  return false;

我的控制器(相关部分)


public function upload() 
    
    
  // variabele om foutmelding bij te houden
  $error = '';

  // controleer of er iets in de $_POST zit
  if(!empty($_POST['action']))
    // controleer of het wel om het juiste formulier gaat
    if($_POST['action'] == 'add-image') 
      // controleren of er een bestand werd geselecteerd
      if (empty($_FILES['image']) || !empty($_FILES['image']['error'])) 
        $error = 'Gelieve een bestand te selecteren';
      

      if(empty($error))
          // controleer of het een afbeelding is van het type jpg, png of gif
          $whitelist_type = array('image/jpeg', 'image/png','image/gif');
          if(!in_array($_FILES['image']['type'], $whitelist_type))
              $error = 'Gelieve een jpeg, png of gif te selecteren';
          
        

        if(empty($error))
        // controleer de afmetingen van het bestand: pas deze gerust aan voor je eigen project
        // width: 270
        // height: 480
        $size = getimagesize($_FILES['image']['tmp_name']);
        if ($size[0] < 100 || $size[1] < 100) 
            $error = 'De afbeelding moet minimum 100x100 pixels groot zijn';
        
      

      if(empty($error))
        // map met een random naam aanmaken voor de upload: redelijk zeker dat er geen conflict is met andere uploads
        $projectFolder = realpath(__DIR__);
        $targetFolder = $projectFolder . '/../assets/ads';
        $targetFolder = tempnam($targetFolder, '');
        unlink($targetFolder);
        mkdir($targetFolder, 0777, true);
        $targetFileName = $targetFolder . '/' . $_FILES['image']['name'];

        // via de functie _resizeAndCrop() de afbeelding croppen en resizen tot de gevraagde afmeting
        // pas gerust aan in je eigen project
        $this->_resizeAndCrop($_FILES['image']['tmp_name'], $targetFileName, 100, 100);
        $relativeFileName = substr($targetFileName, 1 + strlen($projectFolder));
        $data = array(
            'image' => $relativeFileName,
            'title' => $_POST['title'],
            'instructions' => $_POST['stappenplan'],
            'description' => $_POST['ingredienten'],
            'category_id' => $_POST['category'],
        );

        // TODO: schrijf de afbeelding weg naar de database op basis van de array $data

        if (!empty($_POST['action'])) 
          if ($_POST['action'] == 'add-image') 
            // array met data invullen
            $data = array(
              'path' => '/' . $relativeFileName,
              'title' => $_POST['title'],
              'instructions' => $_POST['stappenplan'],
              'description' => $_POST['ingredienten'],
              'category_id' => $_POST['category'],
            );
              
             // aanspreken van de DAO
             $insertImage = $this->uploadDAO->insertImage($data);

             $title = $this->uploadDAO->ImageInsterId($data);
             $this->set('title', $title);

             $ingredientsArray = explode( ',', $data['description'] );
             foreach($ingredientsArray as $ingredient)
               $insertIngredient = $this->uploadDAO->insertIngredients($ingredient , $title);
             
             
             $insertCategory = $this->uploadDAO->insertCategory($data, $title);
   
        // TODO 2: zorg dat de variabele $error getoond wordt indien er iets fout gegaan is
          if (!$insertImage) 
            $errors = $this->uploadDAO->validate($data);
            $this->set('errors', $errors);
           else 
            $_SESSION['info'] = 'Thank you for adding a Post!';
            header('Location: index.php?page=detail&id='. $title['id']);
            exit();
          
        
      
    
  

这里也有一些用于图片上传的代码,但它不相关,因为它正在工作。

我的 html

    <span class="error"><?php if(!empty($error)) echo $error; ?></span>
    <section class="upload_box">
        <h1 class="hidden">upload-form</h1>
        <form method="post" action="index.php?page=upload" enctype="multipart/form-data" class="form__box">
            <input type="hidden" name="action" value="add-image" />
            <div class="form-field">
              <label class="upload__title form_container">Kies een afbeelding
              <span class="error"><?php if(!empty($errors['title'])) echo $errors['title'];?></span>
                  <input type="file" name="image" accept="image/png, image/jpeg, image/gif" required  class="upload__button filter__submit input">
              </label>
              </div>
            <div class="form-field">
            <label class="upload__title form_container">Titel
              <span class="error"><?php
               if(!empty($errors['title'])) 
                 echo $errors['title']; ?></span>
              <input type="text" name="title" required  class="upload__title form_field input">
            </label>
            </div> 
            <div class="form-field"> 
                <label class="upload__title form_container">Stappenplan
                  <span class="error"><?php if(!empty($errors['instructions'])) echo $errors['instructions']; ?></span>
                  <textarea name="stappenplan" id="stappenplan" cols="50" rows="5" required  class="form_field upload__title input"></textarea>
                </label>
            </div>
            <div class="form-field"> 
              
              <label class="upload__title form_container">Ingredienten
              <span class="error"><?php if(!empty($errors['description'])) echo $errors['description ']; ?></span>
              <input type="text" TextMode="MultiLine" name="ingredienten" maxlength="255" required  class="form_field upload__title input"  id="ingredienten">
            </label>
            </div>
          
            <div class="category_container">
              <label class="category_label filter__button">
              <input class="category_input" type="checkbox" id="pasta" name="category" value="1">
              Pasta</label>

              <label class="category_label filter__button">
              <input class="category_input" type="checkbox" id="veggie" name="category" value="2">
              Veggie</label>

              <label class="category_label filter__button">
              <input class="category_input" type="checkbox" id="vlees" name="category" value="3">
              Vlees</label>
            </div> 
            <div class="form-field">
              <input type="submit" value="uploaden"  class="filter__button filter__submit">
              <input type="reset" value="wissen"  class="filter__button filter__submit">
            </div> 
          </form>
    </section>

<script src="js/validate.js"></script>

我所知道的: 我知道 recipe_id 不是问题。我对其他 SQL 插入使用相同的方法。 我不想要explode()implode(),因为它们在这种情况下不起作用。 尝试了几个 foreaches 但还没有让它工作,只是还没有。 它也与括号或逗号或其他无关。

当我有 2 个复选框值时,这只是插入只做一次。而且我不知道如何在选择所有 3 个或所有 3 个时使其循环

【问题讨论】:

【参考方案1】:
             <div class="category_container">
              <label class="category_label filter__button">
              <input class="category_input" type="checkbox" id="pasta" name="category[]" value="1">
              Pasta</label>

              <label class="category_label filter__button">
              <input class="category_input" type="checkbox" id="veggie" name="category[]" value="2">
              Veggie</label>

              <label class="category_label filter__button">
              <input class="category_input" type="checkbox" id="vlees" name="category[]" value="3">
              Vlees</label>
            </div>

您需要使用category[],而不仅仅是category 在表单提交中发送多个值。

现在,您可以获取类别的值

$categories = (is_array($_POST['category'])) ? $_POST['category'] : [];

如果没有选中复选框,我已经为类别分配了默认值。

然后使用php的implode函数:

$categories_string = implode(',', $categories);

或根据您在数据库表中的保存方式使用 foreach 循环:

foreach ($category as $category)

  //use each category

【讨论】:

以上是关于将多个复选框插入 MySQL (PDO)的主要内容,如果未能解决你的问题,请参考以下文章

使用 PHP 处理多对多数据库关系并选择/插入多个复选框值 MYSQL

php过滤mysql多个复选框

我正在尝试将复杂复选框表单的值存储在 mysql 数据库中

如何将多个复选框值插入表中?

将多个复选框插入数据库 Html Php

从生成的复选框将多个条目插入数据库