Mysql INSERT and DELETE in a single statement with dependant on eachother - php

I have the following two queries. Second query is dependent on first one.
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
$message = "both queries executed successfully";
}
else
{
$del = mysql_query("delete record inserted by $query1");
}
}
Can we execute these two queries in a single statement so that both queries depend on each other.If INSERT query fail, DELETE query also fail it's execution as well as if DELETE query fail INSERTION in query first fail.
Thanks

If I good understand what you need, simply use transactions.
Run this query before your insertion:
mysql_query('begin');
And then, if everything went fine, commit the transaction:
mysql_query('commit');
In case of any failures, you may rollback every change you made:
mysql_query('rollback');
Note that in case of MySQL, the MyISAM engine does not support rollback in transactions, so use InnoDB.
Read more about transactions here: https://dev.mysql.com/doc/refman/5.0/en/commit.html
Example with your code:
<?PHP
mysql_query('begin'); //start transaction
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
mysql_query('commit'); //both queries went fine, so let's save your changes and end the transaction
$message = "both queries executed successfully";
}
else
{
mysql_query('rollback'); //query2 failed, so let's rollback changes made by query1 and end the transaction
}
}
else
mysql_query('rollback'); //query1 failed, so let's end the transaction

If query2 fails it doesn't check query1.
$query1 = mysql_query("Insert into table_one set ---- ");
$query2 = mysql_query("delete from table_two where condition---");
if( $query2 && $query1)
{
$message = "both queries executed successfully";
}
else if(!$query2)
{
$del = mysql_query("delete record inserted by $query1");
}

You can use transaction, if any query fails then call rollback, otherwise commit

I found a best solution.
Extending idea of #Luki i wrote the following code and it give me too much satisfied answer. First use the following function.
function multi_statement()
{
global $conn;
$total_args = func_get_args();
$args = implode($total_args,";");
$args = "begin;".$args.";commit;";
$number = 0;
if($conn->multi_query($args))
{
do
{
if ($conn->more_results())
{
$number++;
}
}
while($conn->next_result());
}
if($number < (count($total_args)+1))
{
$conn->query('rollback');
echo "Sorry..!!! Error found in Query no:".$number;
}
else
{
echo "All queries executed successfully";
}
}
Then I called the function with number of statements, all these statements are dependent on each other. In-case there is error in any query, no one query occur any changes in database.
$statement1 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as1', 'as1')";
$statement2 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as2', 'as2')";
$statement3 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as3', 'as3')";
$statement4 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as4', 'as4')";
$statement5 = "DELETE from user where user_id = '12'";
multi_statement($statement1,$statement2,$statement3,$statement4,$statement5);

Related

if successfully insert into database, insert into another database PHP

$sql = "INSERT INTO nextofkin(username,password,contact,email) VALUES('$NOKUN','$NOKPW', '$NOKContact', '$NOKEmail')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO users(username,password,role) VALUES ('$NOKUN','$NOKPW', 'nextofkin')";
} else {
$check1='fail';
}
when i run this php only the first sql statement is inserted.
How can i make the second sql statement run when i inserted into the first sql statement?
As #Darren pointed out, you're not actually executing the statement, you're just updating the value of $sql.
$sql = "INSERT INTO nextofkin(username,password,contact,email) VALUES('$NOKUN','$NOKPW', '$NOKContact', '$NOKEmail')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO users(username,password,role) VALUES ('$NOKUN','$NOKPW', 'nextofkin')";
$conn->query($sql);
} else {
$check1='fail';
}

how to do more than query on the same record?

I have this php file to deal with my sql, I want to make many statement on one record in the database
for examole I have this query :
$query = mysql_query("SELECT bloodGroup,quantity,bank_id FROM medical_bank_notification WHERE seen=1");
I want to make all the records which were selected in the $query to have the field seen=0 after it has been selected, so I thought that I have to know all the IDs from the first query and then write another query:
$sql2 = "INSERT INTO medical_bank_notification (seen) VALUES (0) WHERE ID=_????_";
use mysqli_multi_query($con,$query)
$query = "INSERT INTO table1 (column1,column2,column3)
VALUES (value1,value2,value3);";
$query .= "INSERT INTO table2 (column1,column2,column3)
VALUES (value1,value2,value3);";
//excute query
if(mysqli_multi_query($con,$query))
{
while (mysqli_next_result($con) && mysqli_more_results($con))
{
if ($resSet = mysqli_store_result($con)) { mysqli_free_result($resSet); }
if (mysqli_more_results($con)){ }
}
echo 'success';
}

Unable to insert into MySQL for select values

I have a web application in which students are divided into "batches".
I am trying to insert student for particular batch and the batch will be chosen by user by select option. After that student is added to the particular batch, he/she will be added to stdhold table. However, it is only inserting for the first selected value of select option.
<?php
function specialCOn() {
$connew = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connew,'mcqs');
return($connew);
}
if (isset($_POST['add']))
{
$namestd=$_POST['std_name'];
$batchstd=$_POST['batch'];
$FNAME=$_POST['f_name'];
$query3 = "INSERT INTO `$batchstd` VALUES('','$namestd','$FNAME')";
$rsq3 = mysqli_query(specialCOn(),$query3);
mysqli_close(specialCOn());
$queryrollno = "select rollno from `$batchstd` order by rollno desc";
$rsqrollno = mysqli_query(specialCOn(),$querrollno);
$getrollno = mysqli_fetch_array($rsqrollno);
$rollnoto = $getrollno[0];
echo "<script>alert('$batchstd')</script>";
echo "<script>alert('$rollnoto')</script>";
mysqli_close(specialCOn());
//Problem is here
$querystdhold = "INSERT INTO stdhold VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd')";
$rsqhold = mysqli_query(specialCOn(),$querystdhold);
mysqli_close(specialCOn());
if ($rsq3&&$rsqhold)
{
echo "<script> alert('Student Added.');
window.location.assign('addstudent.php');
</script>";
//header('Location:addstudent.php');
}
else
{
echo "<script> alert('You Havenot added Student.');
window.location.assign('addstudent.php');</script>";
}
}
?>
Try use this :
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO ? (col1,col2,col3) VALUES('',?,?)");
$stmt->bind_param('sss', $_POST['batch'], $_POST['std_name'], $_POST['f_name']);
$stmt->execute();
For the detail example you need to read the #Amber Answer how to create secured prepared statement.
Hope this'll help you.
Try specifying the column names in your insert query:
INSERT INTO stdhold (col1, col2, col3, col4) VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd');
For reference see the MySQL Insert documentation.

php pdo insert,update into one table in mean time insert query to other table too

this is the tables
tbl_one
id---int
name-var
tbl_tow
id----int
name--var
this is how it will insert with php pdo,
public function insert() {
$stmt9 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
$stmt9->bindParam(':name' ,$this->name);
$stmt9->execute();
if($stmt9){
echo "Added";
} else {
echo "error";
}
}
here the idia is to insert in both tables in one time, and delete from both tables in one time.
is it possible here
NOTE: i can not use trigger as i have already setup in other case so mysql is not supporting multi trigger in one time or action.
regards
Is this not what you're after?
public function insert() {
$stmt9 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
$stmt9->bindParam(':name' ,$this->name);
$stmt9->execute();
$stmt10 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
$stmt10->bindParam(':name' ,$this->name);
$stmt10->execute();
if($stmt9 && $stmt10){
echo "Added";
} else {
echo "error";
}
}
Basically you double up the queries inside your function, so you can "manually" insert trails to your log table. Sorry if I've misunderstood you.
I assume that you are looking for a transaction.
All changes performed by queries will be live only when you commit a transaction, if something fails you may simply do a rollback and nothing will happen at all.
This is useful if you have inserts in multiple tables and want to be sure that changes are only made when all queries were a success!
Example:
public function insert() {
//This will start a transaction and turn-off auto-commit of queries.
$this->conn->beginTransaction();
$stmt9 = $this->conn->prepare("INSERT into tbl_one (name) VALUES (:name)");
$stmt9->bindParam(':name' ,$this->name);
$stmt9->execute();
$stmt10 = $this->conn->prepare("INSERT into tbl_two (name) VALUES (:name)");
$stmt10->bindParam(':name' , $someOtherName);
$stmt10->execute();
if($stmt9 && $stmt10){
$this->conn->commit(); //This will save your changes
} else {
$this->conn->rollBack(); //This will undo your changes
}
}
Simple as that.

will mysqli->rollback(), rollback every query that has been previously committed?

I want to know if mysqli->rollback will rollback all the queries that have been committed before the rollback.
For example, in the code below, the first query will be committed, but the second query will fail because of misspelling 'username'. Does that mean that the query before the rollback will or will not get executed?
$mysqli->autocommit(FALSE);
$query = "INSERT INTO users (username, password) VALUES ('user123', '1apple')";
$query2 = "INSERT INTO users (**usernam**, password) VALUES ('user987', '2apple')";
if($resrouce = $mysqli->query($query)){
$mysqli->commit();
if($resource2 = $mysqli->query($query2)){
$mysqli->commit();
}else{
$mysqli->rollback();
}
}else{
$mysqli->rollback();
}
Once you commit the transaction , you can not rollback it , you can only rollback the statement which is not comited yet
modify line 8 and add a line in the end in your code:
$mysqli->autocommit(FALSE);
$query = "INSERT INTO users (username, password) VALUES ('user123', '1apple')";
$query2 = "INSERT INTO users (**usernam**, password) VALUES ('user987', '2apple')";
if($resrouce = $mysqli->query($query)){
//$mysqli->commit(); this not necesary
if($resource2 = $mysqli->query($query2)){
$mysqli->commit();
}else{
$mysqli->rollback();
}
}else{
$mysqli->rollback();
}
$mysqli->close();
Personally I find the PDO library better for database access than mysqli. You can check:
http://php.net/manual/en/pdo.begintransaction.php
which does exactly what you need... Hope that helps

Categories