将数据插入到由外键关联的单独表中

Insert data into separate tables related by foreign keys

我有一个包含两个 table 的数据库:

posts:id(主键,自增),title_bg,title_en,body_bg,body_en,status,created,updated

postimage:id(主键,自增),post_id,name

当我不使用外键时,具有多个元素的表单工作正常。它将 post 的所有详细信息填入 posts table 并且多张图片正在上传到 post 图片 table,但它们不是相关,所以 post_id 字段显示 0 值。

当我使用以下查询在 phpMyAdmin 上设置外键时:

ALTER TABLE `postimage` ADD FOREIGN KEY ( `post_id` ) REFERENCES `database_name`.`posts` ( `id` ) ON DELETE RESTRICT ON UPDATE RESTRICT ;

并且当我创建一个新的 post 时,所有值都保存到 post 中 table,除了图像保存到第二个 table 中。 post图像 table 是空的。

这是我的代码:

 <?php
    if(isset($_POST['submit'])) {
        $title_bg = $_POST['title_bg'];
        $title_en = $_POST['title_en']; 
        $body_bg = $_POST['body_bg'];
        $body_en = $_POST['body_en'];

        if(isset($_FILES['image'])) {
            foreach($_FILES['image']['name'] as $key => $name) {
                $image_tmp = $_FILES['image']['tmp_name'][$key];

                move_uploaded_file($image_tmp, '../uploads/' . $name);

                $query = "INSERT INTO postimage(name) ";
                $query .= "VALUES('$name')";

                $upload_images = mysqli_query($connection, $query);
            }    
        }

        $status = $_POST['status'];


        $query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
        $query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";

        $create_post = mysqli_query($connection, $query); 

        header("Location: posts.php");  
    }
    ?>
    <form action="" method="post" enctype="multipart/form-data">
        <div class="form-item">
            <label for="title_bg">Post title BG</label>
            <input type="text" name="title_bg">
        </div>

        <div class="form-item">
            <label for="title_en">Post title EN</label>
            <input type="text" name="title_en">
        </div>    
        <div class="form-item">
            <label for="body_bg">Post body BG</label>
            <textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
        </div>    

        <div class="form-item">
            <label for="body_en">Post body EN</label>
            <textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
        </div>    

        <div class="form-item">
            <label for="image">Image</label>
            <input type="file" name="image[]" multiple>
        </div>

        <div class="form-item">
            <label for="status">Post status</label>
            <select name="status">
                <option value="published">published</option>
                <option value="draft">draft</option>
            </select>
        </div>

        <div class="form-item">
            <input type="submit" class="form-submit" name="submit" value="Submit">
        </div>    
    </form>

我还创建了两个新的 table 作为测试:

老师:id,姓名,content_area,房间

学生:id,姓名,homeroom_teacher

当我在学生字段 homeroom_teacher 上设置外键并从 phpMyAdmin 手动插入数据时,它们变得相关并且学生 table 上的 ID 变得可点击并显示与老师的关系.所以手动它工作得很好,问题出在 PHP 代码中。

我需要更改什么查询,以便与 post 中的 post id table 和 [=51= 中的 post_id 建立连接]图片table?

我知道我缺少 $_FILES 查询中的 id,但我不知道如何获取它,因为它已经是自动自增字段。

谢谢。

我认为这是个问题,因为您首先在 postimage 中添加数据,然后在 post 中添加数据,因此在 postimage 中找不到 post_id 尝试更改 post 查询的离子,例如:`$status = $_POST['status'];

    $query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
    $query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";

    $create_post = mysqli_query($connection, $query);

    if(isset($_FILES['image'])) {
        foreach($_FILES['image']['name'] as $key => $name) {
            $image_tmp = $_FILES['image']['tmp_name'][$key];

            move_uploaded_file($image_tmp, '../uploads/' . $name);

            $query = "INSERT INTO postimage(name) ";
            $query .= "VALUES('$name')";

            $upload_images = mysqli_query($connection, $query);
        }    
    }
<?php

if(isset($_POST['status'])) {
  $status = $_POST['status'];
}

if(isset($_POST['submit'])) {
    $title_bg = $_POST['title_bg'];
    $title_en = $_POST['title_en']; 
    $body_bg = $_POST['body_bg'];
    $body_en = $_POST['body_en'];

$connection =  new mysqli("localhost", "USER_XY", "PASSWD","DB"); 

if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  die ("<h1>can't use Database !</h1>");
  exit();
}
/* change character set to utf8 */
if (!$connection->set_charset("utf8")) {
printf("Error while loading 'character set utf8' : %s\n", $connection->error);
die();
} 

/**
 * First save the Post
 **/
    $query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
    $query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";

      $result=$connection->query($query);
      // verify results
      if(!$result) {
        $message  = "ERROR SAVING POST : ".$connection->error . "\n";
        $connection->close();
        echo ($message);
        return false;
      }   

/**
 * get the last inster id of the Post
 **/        
    $post_id = $connection->insert_id;
    echo "Post id=".$post_id ."<br>\n";
    if(isset($_FILES['image'])) {
        foreach($_FILES['image']['name'] as $key => $name) {
            $image_tmp = $_FILES['image']['tmp_name'][$key];

            move_uploaded_file($image_tmp, './uploads/' . $name);
/**
 * now insert the image with the post_id
 **/                
    $query = "INSERT INTO `postimage` (`id`, `post_id`, `name`) ";
    $query .= "VALUES (NULL, '".$post_id."', '".$name."');";

                      $result=$connection->query($query);
      // verify results
      if(!$result) {
        $message  = "ERROR INSERT IMAGE : ".$connection->error . "\n";
        $connection->close();
        echo ($message);
        return false;
      } 
        }    
    }
    header("Location: upload_posts.php");  
}
?>
<form action="upload_posts.php" method="post" enctype="multipart/form-data">
    <div class="form-item">
        <label for="title_bg">Post title BG</label>
        <input type="text" name="title_bg">
    </div>

    <div class="form-item">
        <label for="title_en">Post title EN</label>
        <input type="text" name="title_en">
    </div>    
    <div class="form-item">
        <label for="body_bg">Post body BG</label>
        <textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
    </div>    

    <div class="form-item">
        <label for="body_en">Post body EN</label>
        <textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
    </div>    

    <div class="form-item">
        <label for="image">Image</label>
        <input type="file" name="image[]" multiple>
    </div>

    <div class="form-item">
        <label for="status">Post status</label>
        <select name="status">
            <option value="published">published</option>
            <option value="draft">draft</option>
        </select>
    </div>

    <div class="form-item">
        <input type="submit" class="form-submit" name="submit" value="Submit">
    </div>    
</form>

可以通过 $mysqli->insert_id; 获得自动增量 ID 有关更多详细信息,请参阅:https://php.net/manual/mysqli.insert-id.php

:-)

使用这个:$last_id = mysqli_insert_id($conn); 获取最后插入的 ID。

 <?php
    if(isset($_POST['submit'])) {
        $title_bg = $_POST['title_bg'];
        $title_en = $_POST['title_en']; 
        $body_bg = $_POST['body_bg'];
        $body_en = $_POST['body_en'];
        $status = $_POST['status'];


        $query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
        $query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";

        $create_post = mysqli_query($connection, $query);

        $last_id = mysqli_insert_id($connection);


        if(isset($_FILES['image'])) {
            foreach($_FILES['image']['name'] as $key => $name) {
                $image_tmp = $_FILES['image']['tmp_name'][$key];

                move_uploaded_file($image_tmp, '../uploads/' . $name);

                $query = "INSERT INTO postimage(post_id, name) ";
                $query .= "VALUES('$last_id', '$name')";

                $upload_images = mysqli_query($connection, $query);
            }    
        }



        header("Location: posts.php");  
    }
    ?>