Executing Multiple or Three Queries at Once - php

I'm currently creating an online reservation system.
How can I execute multiple queries at once?
I'm already using mysqli_muti_query. I have three queries to execute.
<?php
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$sql .= "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye' ";
$sql .= "UPDATE vehicles set status = '$un' WHERE plateno = '$plate' "; ?>

You need to Add semicolon after each statement:
<?php
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$sql .= "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye' ;";
$sql .= "UPDATE vehicles set status = '$un' WHERE plateno = '$plate' ;";

If supported by your database, I'd suggest that you run your queries separately and wrap them into a single transaction.
$conn->begin_transaction();
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$conn->query($sql);
$sql = "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye';";
$conn->query($sql);
$sql = "UPDATE vehicles set status = '$un' WHERE plateno = '$plate';";
$conn->query($sql);
$conn->commit();
I'd also suggest that you use prepared statements with parameters rather than including values directly into your query string.

You can use PHP mysqli_multi_query-function.
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$sql .= "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye' ;";
$sql .= "UPDATE vehicles set status = '$un' WHERE plateno = '$plate' ;";
/* execute multi query */
if ($mysqli->multi_query($query)) {
}

Related

How can I apply MySQL transactions feature using php with it?

I am trying to build a sale invoice page that takes multiple products as input and also some information about the customer. It interacts with four MySQL tables (sales, sale_details, posting, and product_inventory). You'll get the idea of what will happen if a query fails. I want to avoid this. For this purpose I am trying to implement transactions feature of the InnoDB database engine using PHP and MySQL (PHPMyAdmin). Another problem is I've heard that autocommit is turned off by default do I need to turn it ON and then OFF every time I fire a query? Here is my PHP code snippet:
$sal_date = trim($_POST["sale_date"]);
$cust_id = trim($_POST["cust_id"]);
$book_no = trim($_POST["sal_book_no"]);
$rem = $_POST["sal_remarks"];
$st = trim($_POST["sub_total"]);
$disc = floatval($_POST["total_disc"]) + floatval($_POST["adj_disc"]);
$total = trim($_POST["grand_total"]);
$query1 = mysqli_query($link, "INSERT INTO sales
(cust_id, book_no, sale_date, sub_total, discount, total, remarks)
VALUES ('$cust_id', '$book_no', '$sal_date', '$st', '$disc', '$total', '$rem')") or die(mysqli_error($link));
$query2 = mysqli_query($link, "SELECT LAST_INSERT_ID() as last_row") or die(mysqli_error($link));
$sal_id = mysqli_fetch_array($query2);
$sal = intval($sal_id["last_row"]);
$the_query1 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `debit`) VALUES ('SI','$cust_id','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
$the_query2 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `credit`) VALUES ('SI','10002','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
for($count=0; $count<$_POST["total_item"]; $count++)
{
$prod_id = floatval(trim($_POST["product_name"][$count]));
$quantity = floatval(trim($_POST["qty"][$count]));
$disc = floatval(trim($_POST["disc"][$count]));
$query3 = mysqli_query($link, "INSERT INTO sale_details (sal_id, prod_id, quantity, discount) VALUES ('$sal', '$prod_id', '$quantity', '$disc')") or die(mysqli_error($link));
$query4 = mysqli_query($link, "INSERT INTO product_inventory (invoice_id, product_id, qty_out, in_date) VALUES ('$sal', '$prod_id', '$quantity', '$sal_date')") or die(mysqli_error($link));
}
I'll appreciate your suggestions.
You can use this method
mysqli_query($db, "START TRANSACTION");
$query1 = mysqli_query($db, "Query 1");
$query2 = mysqli_query($db, "Query 2");
$query3 = mysqli_query($db, "Query 3");
if($query1 && $query2 && $query3) {
mysqli_query($db, "COMMIT");
} else {
mysqli_query($db, "ROLLBACK");
}

How to run multiple query on single save button?

When I click on the save button only all_university table updates but the all_colleges table has not been updated. How can I update two tables on one save button?
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
$value = mysqli_multi_query($link,$sql);
if($value == true){
$msg .="<h5 style='color:green'>Successfull</h5>";
} else {
$msg .="<h5 style='color:red'>Error!</h5>";
}
}
?>
It doesn't matter how many queries you have. Just run them all one by one.
Besides, you should be using prepared statements.
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = ? where university_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['university_name']);
$stmt->execute();
$sql = "update all_colleges set placement = ? where college_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['college_name']);
$stmt->execute();
$msg .="<h5 style='color:green'>Successfull</h5>";
}
DO NOT use mysqli_multi_query(). It will do you no good and won't work the way you think.
If you want to use the multi-query function, you have to concatenate the two query strings:
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
And then execute mysqli_multi_query.
Or, as Rory already mentioned, just query twice using the normal mysqli_query function.
But you should really look into prepared statements as you are vulnerable to SQL injection!
Separate both query with semicolon (;)
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Then, Append Both Query.
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Execute it.
$value = mysqli_multi_query($link,$sql);
The mysqli_multi_query() function performs one or more queries against
the database. The queries are separated with a semicolon.

Mysqli SELECT INSERT and UPDATE Query simulatenously

Hello I have a Database named as "admin" in which i have two tables
Table 1 Name = "register"
Table 2 Name = "noti"
In Register Table i've approx more than 10+ User entries which comes through Registration Page
In Noti Table, its empty at this time (Column Name is also "noti")
I want to perform this thing
First I want to count the total no. of records in "register" table
and it checks, if the records are greater than ZERO then it runs the INSERT query otherwise it runs the UPDATE Query
And i want to INSERT and UPDATE that count value into "noti" table
Here's my code
<?php
include('config.php');
$sql2 = "SELECT count(*) as count FROM register";
$result2 = mysqli_query($con, $sql2);
if($result2->num_rows>0)
{
while($rw1=$result2->fetch_array())
{
$value1 = $rw1['count'];
$result = mysqli_query($con, "SELECT count(*) as count FROM register ");
if(!empty($value1)) {
mysqli_query($con, "UPDATE noti SET noti = '$value1' ");
}
else
{
mysqli_query($con, "INSERT INTO noti(noti) VALUES ('$value1') ");
}
}
}
?>
Use this:
include('config.php');
$sql2 = "SELECT count(*) as count FROM register";
$result2 = mysqli_query($con, $sql2);
$count = $result->num_rows;
if($count != 0)
{
mysqli_query($con, "UPDATE noti SET noti = '$count' ");
}
else
{
mysqli_query($con, "INSERT INTO noti(noti) VALUES ('$value1') ");
}

My MySQLi dosen't update only inserts? What's wrong with my script?

$check_verified_user = mysqli_query("SELECT * from user_verified where user_mail = '$payer_email'");
$user_verified = mysqli_fetch_array(mysqli_query($conDB, "SELECT * FROM user_verified where user_mail = '$payer_email'"));
if(mysqli_num_rows($check_verified_user) > 0) {
mysqli_query($conDB, "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'");
} else {
mysqli_query($conDB, "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')");
}
I don't know what's wrong with my script, it checks if the row exists, then if it exists it should update, but instead it inserts another row, which i don't understand...
Give this a try.
$query = "SELECT * FROM user_verified WHERE user_mail = $payer_email";
$check_verified_user = mysqli_query($conDB, $query);
You basically wasn't giving it the database connection, so it was always coming back as not being greater than 0 rows. Personally, I always put my query into its own variable first, and this will ensure that you don't forget params for the mysqli_query() function. It also makes it easier to read, and allows you to use the query in other places if needed.
You can do this method:
$sql = "SELECT * from user_verified where user_mail = '$payer_email'";
$result = mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
if (mysqli_num_rows($result)) {
$sql = "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'";
}
else {
$sql = "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')";
}
mysqli_free_result($result);
mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
If your user_mail is a UNIQUE KEY you would be able to use the option ON DUPLICATE KEY UPDATE in the INSERT. You can do everything in just 1 query.
$sql = "INSERT INTO user_verified (user_mail,total_paid) VALUES ('$payer_email',$payment_amount) ON DUPLICATE KEY UPDATE total_paid = total_paid + $payment_amount";
mysqli_query($conDB, $sql);
Check this example of a table using UNIQUE KEY.
http://sqlfiddle.com/#!2/4919e2/1/0

How to execute PHP mysqli multi query by setting variables

I want to execute a multi query in PHP MySQL, and get the result. My queries are like this.
$sql1 = "set #uid:=(select chat_id from chat_notify where online=1 and engaged=0 limit 1);";
$sql1 .= "update chat_notify set engaged=1,emp_id=1 where chat_id=#uid;";
$sql1 .= " select #uid";
$sql = $mysqli->multi_query($sql1);
I want to get the result of the uid in php.
Change your code accordingly
$sql1 = "set #uid:=(select chat_id from chat_notify where online=1 and engaged=0 limit 1)";
$sql2 = "update chat_notify set engaged=1,emp_id=1 where chat_id=#uid";
$sql3 = "select #uid";
$mysqli->query($sql1);
$mysqli->query($sql2);
$res = $mysqli->query($sql3);
and then get your query result usual way

Categories