获取外键

时间:2019-09-08 20:27:44

标签: php sql

我是大学自学的程序员,几天后我感到非常困惑。我正在工作列表网站的后端。该用户将能够发布工作,并且我有三个表:jobskeywordsrequirementsjob_idjobs的主键,也是keywords表中的外键。目前,我只能在jobs表中插入数据,而不能在keywords表中键入任何内容。每个job_id可以有多个keyword

SQL-作业表

CREATE TABLE `jobs` (
  `title` text NOT NULL,
  `type` text NOT NULL,
  `location` text NOT NULL,
  `salary` int(11) NOT NULL,
  `description` text NOT NULL,
  `date` date NOT NULL,
  `job_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=latin1;

SQL-关键字表

    CREATE TABLE `keywords` (
          `keyword_id` int(11) NOT NULL AUTO_INCREMENT,
          `keyword` text NOT NULL,
          `job_id` int(11) NOT NULL,
          PRIMARY KEY (`keyword_id`),
          KEY `job_id` (`job_id`),
          CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`job_id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;

PHP (我知道代码尚不安全,但我只是想先了解一下)

<?php
    require("../config/db.php");
    require("add-jobs.php");



    $link = mysqli_connect("localhost","root","","benoit");


    $title = $_POST["position"];
    $type = $_POST["job-type"];
    $location = $_POST["location"];
    $salary = $_POST["salary"];
    $description = $_POST["description"];
    $date = $publisheddate;

    $keywords = $_POST["keywords"];


    mysqli_query($link,"INSERT INTO jobs (`title`, `type`, `location`, `salary`, `description`, `date`)
    VALUES ('$title', '$type', '$location', '$salary', '$description', CURDATE())") 
    or die(mysqli_error($link));


    foreach ($keywords as $keyword){
        mysqli_query($link, "INSERT INTO keywords (`keyword`) VALUES ('$keyword')");
    }
    ?>

1 个答案:

答案 0 :(得分:0)

使用$mysqli->insert_id获取插入ID并使用它:

strcmp