0

I have 3 tables (aluno, matricula and agregado_familiar) and i´m trying to delete one entity from the first one, but it have foreign keys to the other tables. I tryied to delete them with this code and didn´t work:

$sql ="DELETE * from matricula,aluno_agregado,aluno WHERE n_processo=$n_processo";
$result = DBExecute($sql);
return $result;

I tryied this too:

$sql ="DELETE FROM matricula WHERE n_processo=$n_processo";
$sql1 ="DELETE FROM aluno_agregado WHERE n_processo=$n_processo";
$sql2 ="DELETE FROM aluno WHERE n_processo=$n_processo";
$result = DBExecute($sql,$sql1,$sql2);
return $result;

I´m not sure if this is possible, but if i don´t delete from the 3 tables it will not let me delete the "aluno". I tryied to do a join too, but I don´t know how to do it.

Table alunos

Table matricula

Table Agregado

Donutsrool
  • 80
  • 7
  • You could do 3 seperate deletes inside a transaction – RiggsFolly Jun 27 '19 at 20:32
  • I tryed to do 3 deletes like DELETE ....; DELETE....; DELETE...., and dind´t work.. – Donutsrool Jun 27 '19 at 20:33
  • Why didn't it work? Is there a foreign key relationship? Make sure you delete from the child table before the parent table. – Barmar Jun 27 '19 at 20:33
  • If you have ON DELETE CASCADE in the foreign key, you only need to delete from the parent table and the child rows will be deleted automatically. – Barmar Jun 27 '19 at 20:34
  • I deleted from the second tables first, and the primary then.. but did not work.. – Donutsrool Jun 27 '19 at 20:34
  • Also `DELETE * FROM table` is syntactically incorrect. Do `DELETE FROM table` – RiggsFolly Jun 27 '19 at 20:35
  • MySQL's [official documentation](https://dev.mysql.com/doc/refman/8.0/en/delete.html) for DELETE covers this, That said, if your original query were modified to work, it would probably remove all rows from the two tables that do not "own" n_processo. – Uueerdo Jun 27 '19 at 20:37
  • **WARNING**: This has some severe [SQL injection bugs](http://bobby-tables.com/) because user data is used inside the query. Whenever possible use **prepared statements**. These are quite straightforward to do in [`mysqli`](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [PDO](http://php.net/manual/en/pdo.prepared-statements.php) where any user-supplied data is specified with a `?` or `:name` indicator that’s later populated using `bind_param` or `execute` depending on which one you’re using. **NEVER** put `$_POST`, `$_GET` or any user data directly in your query. – tadman Jun 27 '19 at 22:32
  • Can´t do it.. I tryed everything i could... if someone knows how to do it.. thanks. – Donutsrool Jun 27 '19 at 22:35

0 Answers0