How to insert in 3 tables at the same time? (PHP + Mysql)

1

I always come here for research but never had to ask. Now I am at a crossroads.

I need to add data in 3 tables at the same time (books, author and editor), and in book, I have a foreign editor and author key.

In sql I got something like this:

INSERT INTO autor(nome) VALUES ('testeAutor');
INSERT INTO livros(titulo, edicao, id_autor) values ('nomedolivro','segunda edicao',LAST_INSERT_ID());
INSERT INTO editora(nome) VALUES('testeEditora');
UPDATE livros set id_editora=LAST_INSERT_ID() where titulo='nomedolivro';

In php, I even got something like this and it worked:

$query_autor = "insert into autor (nome) values ('$autor')";
            $sql_autor = mysqli_query($con, $query_autor) or die("Não foi possível cadastrar o autor.");
            $id_autor = mysqli_insert_id($con);
            $query_editora = "insert into editora (nome) values ('$editora')";
            $sql_editora = mysqli_query($con, $query_editora) or die("Não foi possível cadastrar a editora.");
            $id_editora = mysqli_insert_id($con);
            $sql = "insert into livros (titulo, edicao, id_autor, id_editora) values ('$titulo', '$edicao', '$id_autor', '$id_editora')";
            echo $sql;
            $result = mysqli_query($con, $sql) or die("Não foi possível inserir o novo livro no sistema.");
            if(!$result) {
                echo "Não foi possivel cadastrar o novo livro";
            } else {
            echo "Livro cadastrado com sucesso";
            echo "<br />";
            echo "<a href='cadastro.php'>Voltar para cadastro</a>";
            echo "<br />";
            echo "<a href='index.php'>Listar todos</a>";

Is there some way less "Gambiarra" and / or more secure to do this? Even because, it can happen to insert the author, editor and the book fails ... I tried begin tran, start transaction ... Nothing works on xampp. If I push either one of them (I looked it up in Google, I looked at the mysql doc), it says the code is incorrect on the next line after BEGIN or START.

Thanks in advance for your attention!

Update: I got to work with START TRANSACTION; + COMMIT; via SQL but wanted to know if it has any more correct or usual way of putting this in php. This is a zone like that I posted on top. Would I have to create another variable just pro START TRANSACTION or have some command in php to do this? I do not know exactly how to google search about it.

    
asked by anonymous 14.07.2017 / 22:50

1 answer

0

As far as I know MySQL does not support some way to insert into multiple tables at the same time.

What you can do is open a transaction, run the inserts, and then commit. Therefore, if an error occurs in one of the inserts the others will not be effectively recorded in the bank.

    
14.07.2017 / 23:14