简体   繁体   中英

How can I perform many-to-many insert using MySQL an PHP?

I have a many-to-many MySQL database with three tables entry, tag, and entry_tag.
entry table has id INT AUTO_INCREMENT PRIMARY KEY, title TEXT and entry TEXT columns
tag table has id INT AUTO_INCREMENT PRMARY KEY and tag VARCHAR(15) columns
entry_tag is a mapping tables between entry and tag, and has entry_id INT and tag_id INT, entry_id and tag_id creates PRIMARY KEY.

Now, I would like to INSERT entry.title and entry.entry and related tags tag.tag to the database and respective tables. I would also like to INSERT appropriate mapping information into entry_tag table. Could anyone tell me how can I possible do it? I am using PHP. How can I get the entry.id and tag.id and link them together in the mapping table?

I have:

$sql_query = "INSERT INTO entry SET
    title = '$title',
    entry = '$entry'";

if (!mysqli_query($link, $sql_query)) {
    $error = 'Error adding submitted entry.';
    include 'includes/error.html.php';
    exit();
}

$sql_query = "INSERT INTO tag SET
    tag = '$tag'";

if (!mysqli_query($link, $sql_query)) {
    $error = 'Error adding submitted entry.';
    include 'includes/error.html.php';
    exit();
}

Now, I would like to perform:

$sql_query = "INSERT INTO entry_tag SET
    entry_id = '$entry.id',
    tag_id = '$tag.id'";

But I stuck on getting the right $entry.id and $tag.id.

使用mysql_insert_id()捕获最后一个插入的ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM