When i paste this into MySql console
START TRANSACTION;
INSERT INTO `orders` (customer_id) VALUES ('2');
SET #lastid=LAST_INSERT_ID();
INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES (#lastid,'3','2','4','4','2');
INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES (#lastid,'1','3','5','4','2');
COMMIT;
it works fine, when i try to do the same via php
$sql = "START TRANSACTION;";
$sql .="INSERT INTO `orders` (customer_id) VALUES ('$customer_id_form');";
$sql .="SET #lastid=LAST_INSERT_ID();";
foreach ($product_id_form as $key => $product){
$sql .= "INSERT INTO `transactions`
(order_id,product_id,product_quantity,price,ammount,customer_id)
VALUES
(#lastid,'$product','$quantity_form[$key]',
'$price_form[$key]','$amount_form[$key]','$customer_id_form');";
}
$sql .= "COMMIT;";
//$sql = "INSERT INTO products (`product_name`,`curent_price`,`product_quota`) VALUES ('$productname_form','$productprice_form','$productquote_form')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
header("Location: order.php");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
mysqli_close($con);
it does not work error shown is
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'INSERT INTO orders (customer_id) VALUES ('2');SET
#lastid=LAST_INSERT_ID();INS' at line 1
Perform the queries one at a time; do not try to send them all at once to the server. The START...COMMIT will determine the transactional semantics.
I think you need multi_query, to execute multiple queries
Related
I have a php results page which gets values from submited php form like
$sales = mysqli_real_escape_string($link, (int)$_POST['sales']);
I have an insert query
$sql = "INSERT INTO daily (date, sales) VALUES (CURRENT_TIMESTAMP, '$sales')";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
Now i want to add an extra field to db which will be based on a new select query
$query = "SELECT SUM(sales) FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
I've tried to add it to insert sql with no result
$sql = "INSERT INTO daily (date, sales, total_sales) VALUES (CURRENT_TIMESTAMP, '$sales', '$query')";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You could use a insert/select
$sql = "INSERT INTO daily (date, sales, total_sales)
SELECT
CURRENT_TIMESTAMP,
'$sales',
SUM(sales)
FROM daily
WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
in two step you could execute your, query get the value and assign to insert ... eg:
$query = "SELECT SUM(sales) as tot FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'";
mysqli_query($link, $query) ;
$row = mysql_fetch_array($result, MYSQL_NUM);
$myTotal = $row[0]
$sql = "INSERT INTO daily (date, sales, total_sales) VALUES (CURRENT_TIMESTAMP, '$sales', '$myTotal')";
You should run that query first, save the results in an array, cycle through the array and add the result in the correct field of your database.
what you are doing now is to add the text of your query in the total_sales column of your daily table.
You can refer to this answer to inspire yourself: Get sum of MySQL column in PHP
Also this page explains very well what you have to do, scroll down until you reach the example titled "Inserting the result of a query in another table with group by".
The code that worked was simple:
$result= mysqli_query($link, "SELECT SUM(sales) as valuesum FROM daily);
$row = mysqli_fetch_assoc($result);
$total_sales = $row['valuesum'];
I couldn't manage it to work because there was other errors which i found from phpfpm-error.log
Try this way:
$sales = mysqli_real_escape_string($link, (int)$_POST['sales']);
$query = "SELECT SUM(sales) FROM daily WHERE date BETWEEN '2017-01-01' AND '2017-01-31'"
$sql = "INSERT INTO `daily` SET `date` = CURRENT_TIMESTAMP, `sales` = ' ".$sales." ', `total_sales` = ($query)";
if(mysqli_query($link, $sql)){
"Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
Upon using this SQL query:
if($count2==0){
//If No Data For Current AF And Date Exists
$sql="INSERT INTO `workhours` (`Date`, `AFNumber`, `Name`, `IN`, `OUT`, `WorkingHours`, `Overtime`, `Status`, `Location`) VALUES('$expldate[1]/$expldate[0]/$expldate[2]', '$afnbr', '$name', '$firstin[0]:$firstin[1]', '$lastout[0]:$lastout[1]', '$totalworkhours:$totalworkmins', '$overtime[0]:$overtime[1]', '$status', '$location')";
if ($con->query($sql) === TRUE) {
echo "Data inserted<br>";
}else {
echo "Error: " . $sql . "<br>" . $con->error."";
}
}else{
//If There Exists Data For Current AF And Date
$sql="UPDATE workhours SET Date='$expldate[1]/$expldate[0]/$expldate[2]', AFNumber='$afnbr', Name='$name', IN='$firstin[0]:$firstin[1]', OUT='$lastout[0]:$lastout[1]', WorkingHours='$totalworkhours:$totalworkmins', Overtime='$overtime[0]:$overtime[1]', Status='$status', Location='$location' WHERE AFNumber='$afnbr'";
if ($con->query($sql) === TRUE) {
echo "Record updated successfully<br>";
} else {
echo "Error updating record: " . $con->error;
}
}
I'm receiving this error:
Notice: Undefined variable: location in
C:\xampp\htdocs\pp\login\code\upload.php on line 284 Error updating
record: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'IN=':', OUT=':', WorkingHours='0:0', Overtime='Check
Schedule:Error', Status='Ch' at line 1AF1110:07/09/2015
Any help plese?
I received the error after adding IN and OUT
IN, OUT are reserved keywords. Try with -
`IN`='$firstin[0]:$firstin[1]', `OUT`=':', ...
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);
Hello i have a problem with my query ill keep getting errors from my query
this is my error;
Error: BEGIN; INSERT INTO our_work (id) VALUES ('6'); INSERT INTO
our_work_portf_img (portf_id, img_id) VALUES ('6', '7'); INSERT
INTO our_work_images (img_id, image) VALUES ('7', 'adawd.jpg');
COMMIT; You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'INSERT INTO our_work (id) VALUES ('6'); INSERT INTO `our_wo'
at line 3
i've tried many things but i noticed one thing if i copy the $query string and i posted the query directly in mysql the problem will not accorded and it works just how i hoped it would.
Does anyone noticed the problem in my query cause im literal out of ideas.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit_new_img'])){
$pjt_dtls = $_POST['project_details'];
$categories = $_POST['categories'];
$link = $_POST['link'];
$image_path = "adawd.jpg";//$_POST['file']; //$_POST['image'];
$row_id ='6';//++$num_rows['i'];
$image_id ='7'; //++$num_rows['ii'];
$sql = "
BEGIN;
INSERT INTO `our_work`
(`id`)
VALUES
('{$row_id}');
INSERT INTO `our_work_portf_img`
(`portf_id`, `img_id`)
VALUES
('{$row_id}', '{$image_id}');
INSERT INTO `our_work_images`
(`img_id`, `image`)
VALUES
('{$image_id}', '{$image_path}');
COMMIT;
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
$conn->query($sql) does not work with multi-query like yours
you need to use multi_query instead
also here is nice comment:
Please note that there is no need for the semicolon after the last
query. That wasted more than hour of my time...
I want to modify my code so instead of just inserting a new row in the MySQL table, it can check to see if there is one with the same item number, and update it.
php code
<?php
$con=mysqli_connect("localhost","root","root","inventory");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
You can use ON DUPLICATE KEY UPDATE syntax,
$sql = "
INSERT INTO `current stock` (ItemNumber, Stock)
VALUES ('$_POST[ItemNumber]', '$_POST[Stock]' )
ON DUPLICATE KEY UPDATE
Stock = '$_POST[Stock]'
";
ItemNumber should be primary/unique key in this case