Get id of the last sale and register in the codvenda field of the items table.

1

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

In the sales table I have the id, codclient, date and total fields.

In the itemvenda table I have the fields id, codvenda, quant, price.

My question is how to get the contents of the id field from the sales table, and save it in the codvenda field of the itemvenda table, since both are recorded simultaneously in the act of issuing the boleto bancário.

If friends can give me a light in this doubt, I will be very grateful.

I'm using mysql and php.

Thank you for the attention of your friends.

    
asked by anonymous 18.12.2015 / 17:59

2 answers

1

Use mysql_insert_id - Gets 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: Because mysql_insert_id () acts on the last query   be sure to call mysql_insert_id () immediately.   after the query that generated the value.

     

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

    
18.12.2015 / 18:05
1

With the tip of Durtto and a lot of kick (Rs ...), I was able to get the id of the sale and save it in the codvenda field of the itemvenda table.

The php code is the same:

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

    
18.12.2015 / 22:17