Is it possible to insert and remove at the same time on the same php page?

Asked

Viewed 151 times

0

Good, at the moment I’m doing a project with html, php and mysql and I’m having a little problem now.

Getting to the point:
Assuming I have two tables: unconfirmed and confirmed, and what I want is, on the php page manage to pass the unconfirmed table data to the confirmed, but when passing the data to the confirmed table I wanted that record to disappear from the unconfirmed table. (in this case the unconfirmed table is called "guest").

Excuse the way I’ve arranged to try to explain, in case you don’t notice something, say I try to explain myself better.

<?php

include ('ligar.php');
$sql = "select * from hospede";
$cod_hospede=$_GET['cod_hospede'];

$sql = "INSERT INTO confirmados SELECT * FROM hospede WHERE cod_hospede = '$cod_hospede'";


$result = mysqli_query($con, $sql);

if ($result)
echo "<br><br>Dados registados com sucesso!";
else
echo "Erro ao tentar registar dados na base de dados!";
?>
<br>
<a href="confirmados.php">voltar</a>
  • With your code it already inserts? If yes, just delete after. Do this within a transaction to not have future problems.

  • Yes, it inserts and it actually goes to the other table, but I want you to delete it from the unconfirmed table. I already tried to delete but gave me error (in this case, it did not go to the other table and was simply removed).

2 answers

0

Just you now play the code to remove from the table you want to remove

$sql2 = DELETE FROM hospede WHERE cod_hospede = '$cod_hospede'";
$result2 = mysqli_query($con, $sql2);

But take a look at Mysql Transactions, this ensures that the two SQL commands are executed, or else neither... helps ensure you won’t lose any data...

0


Yes, it is possible. Create two queries

$insert_sql = "INSERT INTO confirmados SELECT * FROM hospede WHERE cod_hospede = '$cod_hospede'";
$result1 = mysqli_query($con, $insert_sql);

$delete_sql = "DELETE from hospede WHERE cod_hospede = '$cod_hospede'";
$result2 = mysqli_query($con, $sql);

Alternatively you could use transactions with both mysqli and PDO.

Using mysqli:

<?php
$mysqli = new mysqli("127.0.0.1", "my_user", "my_password", "dbname");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}
try{
   $mysqli->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);

   $mysqli->query("INSERT INTO confirmados SELECT * FROM hospede WHERE cod_hospede = '$cod_hospede'");
   $mysqli->query("DELETE from hospede WHERE cod_hospede = '$cod_hospede'");

   $mysqli->commit(); 
} catch (Exception $e) {
// Exceção lançada, rollback na transação
   $db->rollback();
}
$mysqli->close();
?>
  • I was able to do what I wanted with the help of your first argument, thank you very much and all those who responded to help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.