简体   繁体   中英

inserting into two different mysql tables using php

I have 2 mysql tables: details and detimages . Details table has a column named id which is a primary key of that table and it also auto increments. And detimages table has a column named detkey which is a foreign key which links with id column of details table.

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.

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

$query = $pdo->prepare(sql); $query->execute(); For every type of SQL type you use is a command like $query->lastinsertid();

Maybe for pdo is different and for SQLite.

Search for the query -> lastinsertid();

Or say to us more information of you MySQL connection type, Is it pdo, mysql, mysqli..

You can use either of these:

mysql_insert_id

PDO::lastInsertId

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