将数据插入与外键

时间:2016-07-07 11:03:30

标签: php mysql database phpmyadmin

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

帖子:id(主键,自动增量),title_bg,title_en,body_bg,body_en,状态,已创建,已更新

postimage:id(主键,自动增量),post_id,名称

当我没有使用外键时,具有多个元素的表单工作正常。它将帖子的所有细节填充到posts表中,并且多个图像上传到postimage表中,但它们不相关,因此post_id字段显示0值。

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

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

当我创建一个新帖子时,所有值都保存在posts表中,除了图像到第二个表中。 postimage表是空的。

这是我的代码:

 <?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>

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

老师:id,name,content_area,room

学生:id,name,homeroom_teacher

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

我需要更改哪些查询,以便从posts表和post_id与postimage表建立post id连接?

我知道我错过了$ _FILES查询中的ID,但我不知道如何获取它,因为它已经是自动自动增量字段。

感谢。

4 个答案:

答案 0 :(得分:1)

<?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>

答案 1 :(得分:1)

自动增量ID可以通过$ mysqli-&gt; insert_id获得; 请参阅更多详情:http://php.net/manual/de/mysqli.insert-id.php

: - )

答案 2 :(得分:0)

我认为这是问题,因为你首先在postimage中添加数据,然后在post中添加数据,因此在postimage中找不到post_id尝试更改查询位置,如:`$ 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);
        }    
    }

答案 3 :(得分:0)

使用此:$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");  
    }
    ?>