Take id from last sale and register in the codsale field of the items table.

Asked

Viewed 356 times

1

Hello, I have to register the sales made in two tables, (Sale and Itemvenda).

In the sales table I have the fields id, codcliente, datavenda e total.

In the table itemvenda have the fields id, codvenda, Quant, price.

My question is how to take the content of the id field of the sale table, and record it in the itemvenda table codvenda field, since both are recorded simultaneously at the time of the bank bill issuance.

If friends could shed some light on my doubt, I’d be most grateful.

I’m using mysql and php.

Grateful for the attention of friends.

  • does a precedent for this, where it writes to table A, picks up the id and then will insert in table B already with the id of the first Insert.

  • is using POO?

2 answers

1


Use mysql_insert_id - Get the ID generated by the previous INSERT operation

<?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); 

if (!$link) { die('Erro na conexão: ' . mysql_error()); }

mysql_select_db('mydb'); mysql_query("INSERT INTO mytable (product) 
values ('kossu')"); 

printf(ID inserido = %d\n", mysql_insert_id()); ?>

Note: Due to mysql_insert_id() acting on the last query performed, make sure to call mysql_insert_id() immediately after the query that generated the value.

Note: The Mysql SQL function value LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not restarted between consultations.

  • With your durtto tip, I was able to pick up and view the sale id, but how do I record this same id in the itemvenda table’s codsale field. Has like you. give me a tip. I thank you for your attention.

1

With Durtto’s tip and a lot of kick (Rs...), I managed to get the id of the sale and record in the field codvenda table itemvenda.

So was the php code:

<?php

include '../conexao.php';

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

$codcliente = $_POST['codcliente'];
$datavenda = date("d/m/Y");
$total = $_POST['total'];

$query_insert = mysql_query("INSERT INTO venda (codcliente, total, datavenda) VALUES ('$codcliente', '$total', '$datavenda')")or die(mysql_error());
if($query_insert == ''){
    echo "<script language='javascript'>
          window.alert('Ocorreu um erro ao cadastrar Venda!');
          </script>";
}}

$codvenda = mysql_insert_id();
$codproduto = $_POST['codproduto'];
$quant = $_POST['quant'];
$preco = $_POST['preco'];

mysql_query("INSERT INTO itemvenda (codvenda, codproduto, quant, preco) values ('$codvenda', '$codproduto', '$quant', '$preco')");
//printf("Last inserted record has id %d\n", mysql_insert_id());

?>

Thanks Durtto for the tip and everyone a big hug.

  • I’m glad you made it. Congratulations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.