Alex
Alex

Reputation: 91

WP - Catch product ID during _POST process

I am dealing with a $_POST issue creating productrecord. I have two tables:

*PRODUCTS*                 *POSTMETA*

PROD ID       TITLE        PROD ID |  META ID | METAKEY |METAVALUE
------------|--------|     --------|----------|---------|--------                
0001 (AI)   |    AAA |       0001  |     200  |  _stock |    3

The post script I developed can handle to store data into PRODUCTS table but not those into POSTMETA since I can't catch the PROD ID that is generated automatically after the post process.

This is my script

<?php
require '../sys/conn.php';

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

$title=mysqli_real_escape_string($conn, $_POST['title'] )
$qty=$_POST['quantity']---> that should go into postmeta.metavalue

if ($title!=''){

$insert = mysqli_query($conn,"
INSERT INTO products (post_title) 
    VALUES ('$title') ");

header('Location: ../pages/post_ok.html'); 
}
else{
header('Location: ../pages/post_error.html');
}
}
mysqli_close($conn);
?>

Basically I should catch the prodID into PRODUCTS table and store it into prodID of POSTMETA in order to associate the quantity to the product.

Any help?

Upvotes: 0

Views: 26

Answers (1)

Stevish
Stevish

Reputation: 729

You can get the new ID as follows:

$prod_id = mysqli_insert_id( $conn );

Use that right after the insert query.

https://www.php.net/manual/en/mysqli.insert-id.php

You haven't shared much about exactly what you want to happen, but maybe something like this:

$insert = mysqli_query($conn,"INSERT INTO products (post_title) 
               VALUES ('$title') ");
$prod_id = mysqli_insert_id( $conn );
$insert2 = mysqli_query($conn,"INSERT INTO products_meta (prod_id, metakey, metavalue) 
               VALUES ('$prod_id', 'quantity', '$qty') ");

Upvotes: 1

Related Questions