I am trying to update the item quantity after the finished transaction. I have quantity on my item and I wanted to lessen the item quantity depending on the item ordered. the transaction works fine but the problem is the update does not execute and it does not update the quantity of the item in my table.
the code:
<?php
include 'includes/session.php';
if(isset($_GET['confirmation'])){
$confirmation = $_GET['confirmation'];
$p_quantity = $_GET['p_quantity'];
$date = date('Y-m-d');
$conn = $pdo->open();
try{
$stmt = $conn->prepare("INSERT INTO sales (user_id, confirmation, status, sales_date) VALUES (:user_id, :confirmation, :status, :sales_date)");
$stmt->execute(['user_id'=>$user['id'], 'confirmation'=>$confirmation, 'status'=>1, 'sales_date'=>$date]);
$salesid = $conn->lastInsertId();
$stmt = $conn->prepare("UPDATE products SET p_quantity=p_quantity-:p_quantity WHERE id=:id");
$stmt->execute(['p_quantity'=>$p_quantity, 'id'=>$id]);
try{
$stmt = $conn->prepare("SELECT * FROM cart LEFT JOIN products ON products.id=cart.product_id WHERE user_id=:user_id");
$stmt->execute(['user_id'=>$user['id']]);
foreach($stmt as $row){
$stmt = $conn->prepare("INSERT INTO details (sales_id, product_id, quantity) VALUES (:sales_id, :product_id, :quantity)");
$stmt->execute(['sales_id'=>$salesid, 'product_id'=>$row['product_id'], 'quantity'=>$row['quantity']]);
}
$stmt = $conn->prepare("DELETE FROM cart WHERE user_id=:user_id");
$stmt->execute(['user_id'=>$user['id']]);
$_SESSION['success'] = 'Transaction successful. Thank you.';
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
$pdo->close();
}
header('location: profile.php');
?>
Related
I want to update table with max three value and minimum with two values.How it would be possible to update table. I Get values from form, there are three fields for three students. Now all of them having same value when i update them in the database. Now i am trying this why. Dont know it works or not
See my page
$s1_name=$_POST['s1_name'];
$s2_name=$_POST['s2_name'];
$s3_name=$_POST['s3_name'];
$query="update students SET Name=:Name
WHERE ProjectID='$id'
";
try
{
$stmt = $conn->prepare( $query );
$stmt->bindParam(':Name', $s1_name);
$stmt->bindParam(':Name', $s2_name);
$stmt->bindParam(':Name', $s3_name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
It does not work this way. The way you are doing it will result in the query only updating it for $s3_name.
You will have to do your try/catch statement for each query:
<?php
$names = [$_POST['s1_name'], $_POST['s2_name'], $_POST['s3_name']];
$query = "update students SET Name=:Name WHERE ProjectID='$id'";
foreach ($names as $name) {
try
{
$stmt = $conn->prepare($query);
$stmt->bindParam(':Name', $name);
$result = $stmt->execute();
$msg = "Record updated";
}
catch(PDOException $ex)
{
$msg = $ex -> getMessage();
}
}
I have two or more statements on one page of my site. And it does not work properly.
The first code is like that:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
echo $gpname;
}
}
$statement->close();
The problem is when I try to add the second code to it:
if($_GET[buy]=='ch'){
$statement = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement->bind_param('s', $gpname);
$results = $statement->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
My code looks like this, but not working:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
if($_GET[buy]=='ch'){
$statement2 = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement2->bind_param('s', $gpname);
$statement2->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
}
}
$statement->close();
What am I doing wrong? I want to add even more UPDATE querys after selecting.
Ohh, I'm an idiot! That was the mistake:
Instead of
while ($stmt1->fetch()){
};
needs only:
while ($stmt1->fetch());
Here's a working example with some development:
<?php
ob_start();
session_start();
include_once 'dbtest.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli->autocommit(FALSE); //turn on transactions
$stmt1 = $mysqli->prepare("SELECT fbname,fbemail FROM users WHERE fbid = ?");
$stmt1->bind_param("s", $_SESSION['FBID']);
$stmt1->execute();
$stmt1->bind_result($fbname,$fbemail);
while ($stmt1->fetch());
$stmt2 = $mysqli->prepare("INSERT INTO test (name,email) VALUES (?, ?)");
$stmt2->bind_param("ss", $fbname, $fbemail);
$stmt2->execute();
$stmt2->close();
$stmt1->close();
$mysqli->autocommit(TRUE); //turn off transactions + commit queued queries
} catch(Exception $e) {
$mysqli->rollback(); //remove all queries from queue if error (undo)
error_log($e);
}
?>
Thank you anyway!!
getting error for mysql when i am using if else in there. i dont know what should i do and when i am using duplicate condition to update then it not woring i am not be able to find where is error
this is the error which is i am getting.
ERROR:SQLSTATE[HY093]: Invalid parameter number: parameter was not
defined
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("SELECT uniqueid FROM hotelcarttemp WHERE uniqueid=:uniqueid");
$stmt->execute(array(':uniqueid'=>$uniqueid));
$count=$stmt1->rowCount();
echo "count-".$count;
if($count>0)
{
$sql = "UPDATE hotelcarttemp SET `hotelname`='".$hotelname."',`roomtype`='".$roomtype."',`checkin`='".$checkin."',`checkout`='".$checkout."',`Country`='".$Country."',`Destination`='".$Destination."',`price`='".$price."' WHERE uniqueid='".$uniqueid."'";
echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
else
{
$sql = "INSERT INTO hotelcarttemp (timestamp, packageid, uniqueid, hotelname, roomtype, checkin, checkout, Country, Destination, hoteldetail, price)
VALUES ('"
.$timestamp."','"
.$packageid."','"
.$uniqueid."','"
.$hotelname."','"
.$roomtype."','"
.$checkin."','"
.$checkout."','"
.$Country."','"
.$Destination."','"
.addslashes($hoteldetail)."','"
.$price."'
)";
// echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
} here
Your SELECT query where condition is WHERE uniqueid=:uniqueid
And you are binding username to it
$stmt->execute(array(':username'=>$uniqueid));//:username invalid parameter
Change this to
$stmt->execute(array(':uniqueid'=>$uniqueid));
In my shop system I'm using this code to insert in the DB customer order details and the products that belongs to that o:
$connection->beginTransaction();
try
{
$sql = "INSERT INTO orders (customer_id, order_price, order_date, order_hour)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
$query->execute(array
(
$user['user_id'],
$order_price,
$date,
$hour
));
if($query)
{
$id_of_respective_order = $connection->lastInsertId();
$sql = "INSERT INTO purchased_products (order_id, product_name, product_price, quantity, extras)
VALUES (?, ?, ?, ?, ?)";
$query = $connection->prepare($sql);
foreach($_SESSION['cart'] as $product)
{
$extras = null;
$product_price = $product['product_price'] * $product['quantity'];
if($product['extras'] != NULL)
{
foreach($product['extras'] as $extra)
{
$extras .= $extra['extra_quantity'] ."x". $extra['extra_name'] ."<br/>";
$product_price += $extra['extra_total'] * $product['quantity'];
}
}
$query->execute(array
(
$id_of_respective_order,
$product['product_name'],
$product_price,
$product['quantity'],
$extras
));
}
unset($_SESSION['cart']);
echo "<script>alert('Your purchase was completed!');
window.location = '/my-orders.php';
</script>";
}
else
{
echo "<script>alert('An error ocurred while completing your purchase. Please try again!');
window.location = '/my-cart.php';</script>";
}
$connection->commit();
}
catch(PDOException $exception)
{
$connection->rollBack();
echo "<script>alert('An error ocurred while completing your purchase. Please try again!');
window.location = '/my-cart.php';</script>";
}
My question is in regards to code optimization for error checking.
It is recommended that I use if ($query) even with the catch and rollBack as I'm doing? It is necessary or I can use only catch and rollBack because it will check for erros by itself?
You don't need to use if if you have your PDO error set to throwing the exception.
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I have here a code to insert the order of the customer in the orders table and insert the purchased products in that order in the purchased_products table. I want to check if the insertions were made, otherwise undo the changes with PDO rollback(). My code is:
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
];
try
{
$connection = new PDO("mysql:host={$HOST};dbname={$DB_NAME}", $USERNAME, $PASS, $options);
}
$connection->beginTransaction();
try
{
$sql = "INSERT INTO orders (customer_id, customer_name, order_value, order_date)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
$query->execute(array
(
$user_id,
$user['user_name'],
$order_value,
$date
));
$id_of_respective_order = $connection->lastInsertId();
}
catch(PDOException $exception)
{
$connection->rollback();
echo "<script>alert('An error occurred while completing your purchase. Please try again later.');</script>";
}
try
{
$sql = "INSERT INTO purchased_products (order_id, product_name, product_price, quantity)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
foreach($_SESSION['cart'] as $product)
{
$query->execute(array
(
$id_of_respective_order,
$product['product_name'],
$product['product_price'],
$product['quantity']
));
}
}
catch(PDOException $exception)
{
$connection->rollback();
echo "<script>alert('An error occurred while completing your purchase. Please try again later.');</script>";
}
$connection->commit();
Is this way safe? I use a transaction to lock the tables and lastInsertId () to assign the ID of the order to the products that belongs to it. I check the insertions and if something went wrong undo the changes with rollback(). Is my checkout system well prepared and totally safe?
It makes more sence to do all your inserts inside the same Try/Catch and then if the order insert or the order_item insert fails a single catch block will deal with the rollback and any cleanup/reporting that may be required.
The way you had it the order insert could fail and then the order_item insert would still try and run, possibly creating items without a owning order.
try {
$connection = new PDO("mysql:host={$HOST};dbname={$DB_NAME}",
$USERNAME, $PASS);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
$connection->beginTransaction();
try {
$sql = "INSERT INTO orders
(customer_id, customer_name, order_value, order_date)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
$query->execute(array( $user_id,
$user['user_name'],
$order_value,
$date
)
);
$id_of_respective_order = $connection->lastInsertId();
$sql = "INSERT INTO purchased_products
(order_id, product_name, product_price, quantity)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
foreach($_SESSION['cart'] as $product) {
$query->execute(array( $id_of_respective_order,
$product['product_name'],
$product['product_price'],
$product['quantity']
)
);
}
$connection->commit();
}
catch(PDOException $e) {
$connection->rollBack();
echo 'Order creation failed: ' . $e->getMessage();
echo "<script>alert('An error occurred while completing your purchase. Please try again later.');</script>";
exit;
}