如何在上传后的PHP MySQL中将一个ID从一个表链接到另一个表

时间:2018-01-21 22:52:52

标签: php mysql mysqli

我正在创建一个发布系统,用户可以上传帖子并上传图片以显示在帖子页面上。我想要完成的是将正在创建的帖子的post_id附加到与其一起上传的图像中。

我需要做什么才能使用帖子上传的每张图片都链接到该特定帖子的ID?

我使用一个表格来显示帖子信息(标题,描述等)和一张表格。

这是我的upload.php:

<?php
session_start();
$msg = "";

include('../includes/db_connect.php');
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

if(isset($_POST['submit'])){

    // IMAGE UPLOAD

    for($i=0; $i<count($_FILES["images"]["name"]); $i++)
    {
        $filetmp = $_FILES["images"]["tmp_name"][$i];
        $filename = $_FILES["images"]["name"][$i];
        $filetype = $_FILES["images"]["type"][$i];
        $filepath = "images/".$filename;

        move_uploaded_file($filetmp, $filepath);

        $sql = "INSERT INTO images (img_name, img_path, img_type) 
                VALUES ('$filename', '$filepath', '$filetype')";
        $result = mysqli_query($db, $sql);
    }

    // WRITTEN INFORMATION SUBMITTED BY USER
    $title = $_POST['title'];
    $price = $_POST['price']; 
    $description = $_POST['description'];
    $category = $_POST['category'];
    $title = $db->real_escape_string($title);
    $price = $db->real_escape_string($price);
    $description = $db->real_escape_string($description);
    $user_id = $_SESSION['user_id'];
    $description = htmlentities($description);

    if($title && $price && $description && $category){
        $query = $db->query("INSERT INTO post (user_id, title, price, 
                 description, category_id) 
                 VALUES('$user_id', '$title', '$price', '$description', 
                 '$category')");
        if($query){
            echo "product posted";
        }else{
            echo "error";
        }
    }else{
        echo "missing data";
    }
}
?>

这是我的帖子表的样子(主键是post_id):

CREATE TABLE `post` (
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`price` varchar(255) NOT NULL,
`category_id` int(11) NOT NULL,
`description` text NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

这是我的图像表(主键是img_id):

CREATE TABLE `images` (
`img_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`img_name` varchar(500) NOT NULL,
`img_path` varchar(500) NOT NULL,
`img_type` varchar(200) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

0 个答案:

没有答案