How to execute two sql queries in php?

542 Views Asked by At

I am trying to execute this code in a php page to store some data on my database. The thing is that I want to Insert data, but due to a foreign key constraint it is impossible. So, in my php code I want to execute two sql queries. The first one to disable foreign key checks and the second one to insert the data.

When I try it in phpmyadmin it works. But manually. I would like to put it on php code.

This is my code. The parameter $conexion is the one that executes my sql queries.

Any ideas?

$sql = "SET foreign_key_checks=0";
$sql. = "INSERT INTO routes (title, distance, subtitle) VALUES ('".$_POST['title']."','".$_POST['distance']."', '".$_POST['subtitle']."');";

$conexion->multi_query($sql);
2

There are 2 best solutions below

0
On BEST ANSWER

Try to avoid using multi_query. Sending a small query to the MySQL server doesn't really affect performance and does prevent kind of limit the effect of something like SQL injection.

In your case there's no need for multi_query. If you send two queries in a script, both go over on the same connection. The SET query affect the current connection.

// Protect against SQL injection
$title = $conexion->escape_string($_POST['title']);
$distance = $conexion->escape_string($_POST['distance']);
$subtitle = $conexion->escape_string($_POST['subtitle']);

// Execute queries
$conexion->query("SET forgeign_key_checks=0");
$conexion->query("INSERT INTO routes (title, distance, subtitle) VALUES ('$tittle', '$distance', '$subtitle')");
0
On

Apart from the comment above, you need a semi-colon between your sql statements

multi_query - Executes one or multiple queries which are concatenated by a semicolon.