简体   繁体   English

使用 php 插入两个不同的 mysql 表

[英]inserting into two different mysql tables using php

I have 2 mysql tables: details and detimages .我有 2 个 mysql 表: detailsdetimages Details table has a column named id which is a primary key of that table and it also auto increments.详细信息表有一个名为 id 的列,它是该表的主键,它也会自动递增。 And detimages table has a column named detkey which is a foreign key which links with id column of details table.并且 detimages 表有一个名为 detkey 的列,它是一个与 details 表的 id 列链接的外键。

What I'm trying to achieve: the user enters the details and also choose the images which is related to the details he entered and then the details gets inserted in the details table and the images which is related to the details gets inserted in the detimages tables with the details id as the foreign key.我要实现的目标:用户输入详细信息并选择与他输入的详细信息相关的图像,然后将详细信息插入到详细信息表中,将与详细信息相关的图像插入到 detimages以详细信息 id 作为外键的表。

I'm able to insert in those two different tables but i'm stuck on the foreign key one.我可以插入这两个不同的表,但我被困在外键上。 I don't know how i can automatically get the primary key of the inserted details and then use it to insert into the detimages table.我不知道如何自动获取插入详细信息的主键,然后使用它插入到 detimages 表中。 Thank you谢谢

Here are my codes:这是我的代码:

 include 'DatabaseConfig.php'; 
    if (isset($_POST['uploadImageBtn'])) {
$details = mysqli_real_escape_string($db, $_POST['details']);        
   $detail_query= "INSERT INTO details(description) values('$details')";        
   $run = $db->query($detail_query) or die("Error in saving detail".$db->error);
    $uploadFolder = 'upload/';
    foreach ($_FILES['imageFile']['tmp_name'] as $key => $image) {
        $imageTmpName = $_FILES['imageFile']['tmp_name'][$key];
        $imageName = $_FILES['imageFile']['name'][$key];
        $result = move_uploaded_file($imageTmpName,$uploadFolder.$imageName);

        // save to database
     
        $image_query = "INSERT INTO detimages SET file_name='$imageName' " ;
        $run = $db->query($image_query) or die("Error in saving image".$db->error);
        
    }
    if ($result) {
        echo '<script>alert("Images uploaded successfully !")</script>';
    }
}

When you execute a sql you have something like that当您执行 sql 时,您会遇到类似的情况

$query = $pdo->prepare(sql); $query = $pdo->prepare(sql); $query->execute(); $查询->执行(); For every type of SQL type you use is a command like $query->lastinsertid();对于每种类型的 SQL 类型,您使用的命令是 $query->lastinsertid();

Maybe for pdo is different and for SQLite.也许 pdo 和 SQLite 不同。

Search for the query -> lastinsertid();搜索查询 -> lastinsertid();

Or say to us more information of you MySQL connection type, Is it pdo, mysql, mysqli..或者告诉我们您的更多信息 MySQL 连接类型,是 pdo, mysql, ZD51E8A0B95EE5528AC7.DE3FDBCA

You can use either of these:您可以使用以下任何一种:

mysql_insert_id mysql_insert_id

PDO::lastInsertId PDO::lastInsertId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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