Save data to multiple tables

1

I am doing a registration system and would like some help from you in order to save the data in several tables.

My registration is composed of the following fields.

Nome do Paciente
Nome do Doutor
Tipo de Serviço
Data de Entrada
Estagio

Now this is my database table:

id_paciente nome_do_paciente nome_do_doutor

This data will be saved in the patient and precise table of the id of that record to give sequence.

id_servico tipo_servico data_servico id_paciente

This data will be saved in the service table and I also need the id of that record.

id_estagio id_servico data_estagio tipo_estagio

This data will be saved in the stage table and I also need the id of this record.

Abre_Conexao();

if (@mysql_query(INSERT INTO cad_paciente VALUES (NULL, $nome_paciente, $nome_doutor))) {

    if(mysql_affected_rows() == 1){
        echo "Registro efetuado com sucesso<br />";
    }

}

I've seen it working this way below, but I want to add to this pattern because my code is all in it.

$query1 = "INSERT INTO paciente VALUES ('NULL, $nome_paciente, $nome_doutor')";
mysql_query( $query1 );

$id_paciente = mysql_insert_id();

$query2 = "INSERT INTO servico VALUES ('NULL, tipo_servico, data_servico,{$id_paciente})";
mysql_query( $query2 );

$id_servico = mysql_insert_id();

$query3 = "INSERT INTO estagio VALUES ('NULL, {$id_servico}, data_estagio, tipo_estagio')";
mysql_query( $query3 );
    
asked by anonymous 05.05.2016 / 20:35

2 answers

1

I think PHP has a native function (mysql_insert_id) to return the generated ID.

Try to take a look at this documentation: link

ex.

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

if (!$link) {

die('Could not connect: ' . mysql_error());

}

mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
    
05.05.2016 / 22:00
0

do so:

if (mysql_query("INSERT INTO cad_paciente VALUES (NULL, "$nome_paciente", "$nome_doutor"))) {

    if(mysql_affected_rows() == 1){
        echo "Registro efetuado com sucesso<br />";
    }

}

However, after studying a little more of PHP and MySQL and getting everything working, look for another method of entering the data or at least validating the data before doing things like this, as this method allows a type of attack called SQL Injection.

    
05.05.2016 / 21:18