How to get ID from another table and INSERT another?

10

I have two tables: destinations and entry:

  • In the destinations table: dest_id (AI) and destination;
  • In the entry table: id (id), target_id (relative to destination id of the destinations table)

I created a query to insert the first form field (destination) into the destinations table

$sqlinsert1 = mysql_query("INSERT INTO 'destinos' VALUES('', '$destino')");

I created a second query to fetch the newly created row:

$another_id = mysql_query("SELECT * FROM 'destinos' WHERE destino = '$destino'");

And a third query to insert data into the input table:

 $sqlinsert2 = mysql_query("INSERT INTO 'entrada_pt' VALUES('', '$another_id')");

Only when checking the entry table, nothing is inserted, other than the destinations table, which is populated.

How to get the id of the first table and insert it into the second table?

    
asked by anonymous 11.04.2014 / 02:18

3 answers

14

First, the answer:

To get the ID of the last entry, just use mysql_insert_id()

$sqlinsert1 = mysql_query("INSERT INTO 'destinos' VALUES('', '$destino')");
$id_destino = mysql_insert_id();

$sqlinsert2 = mysql_query("INSERT INTO 'entrada_pt' VALUES('', '$id_destino')");

One remark:

This code does not make sense.

$another_id = mysql_query("SELECT * FROM 'destinos' WHERE destino = '$destino'");

The mysql_query() function does not have the ID of the record inserted, but a pointer to a result set.

To use your 2nd query, instead of mysql_insert_id() , you would need this:

$sqlselect1 = mysql_query("SELECT * FROM 'destinos' WHERE destino = '$destino'");
$row = mysql_fetch_assoc($sqlselect1);
if ($row)
   $another_id = $row['id'];

The most important:

  

No one should be using the mysql_ functions in PHP anymore!
  They are insecure * and obsolete, and are no longer available from PHP 5.5.   Use the mysqli_ !

* Actually the functions themselves are not insecure, but are used insistently in the worst way. There are people who exchange lib , but still put PHP variables directly inside SQL. Ideally, you should only use binding .

    
11.04.2014 / 02:23
1

The mysql_ * functions are obsolete and it is recommended to use mysqli or PDO. In this question has a list of arguments to DO NOT use them.

To get the last inserted id use the function mysql_insert_id ()

$sqlinsert1 = mysql_query("INSERT INTO 'destinos' VALUES('', '$destino')");
$id_destino = mysql_insert_id();
$sqlinsert2 = mysql_query("INSERT INTO 'entrada_pt' VALUES('', '$id_destino')");
    
11.04.2014 / 02:27
0

You can use yes !! The only difference is to change mysql_ by mysqli _.... and put the connection link, as below.

include 'conexao.php';

//$conn é a variavel de conexão utilizada em conexao.php

$sqlinsert1 = mysql_query("INSERT INTO 'destinos' VALUES('', '$destino')");

$id_destino = mysql_insert_id($conn);

$sqlinsert2 = mysql_query("INSERT INTO 'entrada_pt' VALUES('', '$id_destino')");
    
14.02.2018 / 17:17