IF-ELSE using PHP and SQL - php

I am creating a stock trading game with PHP and SQL. I have a 'buy' function that adds the stock id, user id and quantity to a table named 'ownedstocks'.
I am having trouble in implementing a simple 'If-Else' statement.
Basically, what I want:
If the user id and the stock id of the stock being purchased are already exists in 'ownedstocks' table, then I just want to update the quantity.
Else if no rows exist for the given user id and stock id, then I want to insert a new row.
I have the code but unsure of using IF-ELSE.
Thanks in advance!
<?php
include_once 'header.php';
$user = $_SESSION['user'];
$id = $_SESSION['id'];
$price = $_SESSION['price'];
$amount=$_POST['amount'];
$total = $amount*$price;
$balance = $_SESSION['balance'];
$con=mysqli_connect("localhost","root","usbw","stocktrading");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$newbalance = ($balance - $total);
queryMysql("UPDATE ownedstocks
SET quantity = (quantity+$amount)
WHERE ownedstocks.userid = '$user' and ownedstocks.stockid = '$id'");
queryMysql("INSERT INTO ownedstocks
VALUES ('$user', '$id', '$amount')");
queryMysql("UPDATE members
SET balance = $newbalance
WHERE members.user = '$user'");
echo("You just purchased $id costing $price per stock<br/><br/>
You bought $amount stocks<br/><br/>
To calculate your bill: $price x $amount which equals $total<br/><br/>
You have just spent $total, your new balance is $newbalance <br/><br/>");
?>

What you want is the MySQL INSERT INTO ON DUPLICATE KEY UPDATE function.
Basically:
INSERT INTO ownedstocks values (...) ON DUPLICATE KEY UPDATE amount = amount + '$amount'

Add unique on (user, stock_id):
ALTER TABLE `ownedstocks` ADD UNIQUE (
`user` ,
`stock_id`
);
Then do something like:
INSERT INTO ownedstocks
VALUES ('$user', '$id', '$amount')
ON DUPLICATE KEY UPDATE
`amount` = `amount` + '$amount';

You could use the mysqli.affected-rows variable http://php.net/manual/en/mysqli.affected-rows.php to achieve the IF statement.

Related

I want to update the stock in the database upon clicking submit, but it stores a wrong input

Here is my code to insert the checked values from checkbox to database. I intend to update the stock from another table after I click submit, but it stores an incorrect input. For ex: If I entered 5 quantity on checkout page, instead of decreasing the number of stock, it inputs a negative value of what I entered: -5.. What seems to be the problem here?
<?php
include 'config.php';
$invoice = $_POST['invoiceid'];
if(isset($_POST['submit'])){
$checked_array=$_POST['prod'];
foreach ($_POST['prodname'] as $key => $value) {
if(in_array($_POST['prodname'][$key], $checked_array)){
$product=$_POST['prodname'][$key];
$price= $_POST['price'][$key];
$qty= $_POST['qty'][$key];
$amtpaid = $price * $qty;
$query = "INSERT INTO purchasedproducts SET invoice_id='$invoice', productname='$product', quantity='$qty', amtpaid='$amtpaid'";
$run = mysqli_query($link,$query);
//select product_stock table
$stock_table = mysqli_query($link, "SELECT * FROM product_stock");
$stock = $row['qty_stock'] - $qty;
$update_que = "UPDATE product_stock SET qty_stock='$stock' WHERE product_name='$product'";
$run_update = mysqli_query($link,$update_que);
}
}
}
header('Location: sample.php');
?>
Your query is updating the column value with your "input". What you are wanting is something like this.
$update_que = "UPDATE product_stock SET qty_stock=qty_stock+'$stock' WHERE product_name='$product'";
This is setting the value to its original value plus the input.

How to insert stock quantity and update into another table?

I'm trying to update the quantity of stock when a new stock is added. I'm using array because I want to add more than one product in the page. But the data is not insert into the db and no update on the quantity of stock too. What do I miss on this code?
<?php
include 'db_connection.php';
if(isset($_POST["submit4"])){
foreach($_POST['fk_product'] as $index => $searchid){
$sql="INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal=$_POST['quantity_bal'];
if($quantity_bal==0){
$sql="UPDATE product set quantity_bal= quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal!=0){
$sql="UPDATE product set quantity_bal= quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
$query = mysqli_multi_query($conn,$sql);
if($query){
header("location:product.php");
}
}
}
?>
What you're missing is that you need to concatenate the queries, with the use of = assignment operator, you've just overridden the former string, so it should be like this
foreach($_POST['fk_product'] as $index => $searchid){
$sql = "INSERT INTO supplier (supplier_name, date_in, fk_product, quantity_in) VALUES ('".$_POST['supplier_name']."','".$_POST['date_in']."','".$_POST['fk_product'][$index]."', '".$_POST["quantity_in"][$index]."')";
$quantity_bal = $_POST['quantity_bal'];
if($quantity_bal == 0){
//I'm presuming that the quantity_ori is a variable here 'coz you're trying to sum up with the original to the latest one
$sql .= "UPDATE product set quantity_bal= $quantity_ori + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}else if($quantity_bal != 0){
$sql .= "UPDATE product set quantity_bal= $quantity_bal + '".$_POST["quantity_in"][$index]."' WHERE id_produk = '".$_GET['id']."'";
}
}
We changed the = symbol in your update queries into .= and then your quantity_ori earlier doesn't have the $ symbol, since we're presuming it's a variable, don't forget the $

How to decrement/decrease a seat value in a booking form?

I was wondering how you can decrease a seating value using php/mysqli?
I have setup a basic sessions timetable with customer registration and I wish to display the number seats left (or maximum seating) and have it decrease with each registration of a customer.
Thanks!
I have created a seating row in topics and have a page that displays speakers with topics and session times.
below is the registration php code currently.
if (isset($_POST['Name'])) {
$Name = mysqli_real_escape_string($con,$_POST['Name']);
$Address = $_POST['Address'];
$Phone = $_POST['Email'];
$Email = $_POST['Phone'];
$sql = "insert into registration (Name, Address, Email, Phone) values ('$Name','$Address','$Phone','$Email')";
//echo $sql;
$result2 = mysqli_query($con,$sql);
// get id from last query insert statement auto increment
$RegistrationID = mysqli_insert_id($con);
foreach($_POST['time'] as $sessionsID){
echo $sessionsID;
$sql = "insert into bookings (sessionsID, RegistrationID) values ($sessionsID, $RegistrationID)";
echo $sql;
mysqli_query($con, $sql);
}
<?php
$sql3 = "select Time, SessionID FROM sessions LIMIT 0, 30 ";
$result = mysqli_query($con,$sql3);
while ($row = mysqli_fetch_assoc($result)) {
// $i++;
echo '<input type="checkbox" value='.$row['SessionID'].' name="time[]">'.$row['Time'].'</label>';
}
?>
Here are the steps I'd take:
Create a table (or add to an existing one, depending your DB structure) with a column that contains the number of seats.
Call it from the db into a variable, eg. $seat, at every registration.
Make it $seat--; (decrement by one), or just $seat = $seat - 1;.
Update the DB with the new value.
I do not see you using seat count anywhere. When you have inserted an entry for a ticket confirmed at the same time you have to update the seat count available by subtracting the no of seat booked.
For easy implementation do like this:
Select count of ticket booked.
Update the remaining seat count by total-booked. Do it for each insert of a ticket booked.

Insert data in current table and update another table MySQL

I'm having problem with inserting in purchase table and updating facility table. Let's say, user made a purchase with product_id and product_quantity.
The query is running. But it inserts twice with the same data and not updating facility table.
When user hit submit, I want to insert product_id and product_quantity into purchase table. And updating facility table with product_id and product_quantity that associated with it.
Here is my code
<?php
include 'dbconn.inc.php';
include 'functions.inc.php';
$sql1 = "SELECT * FROM facilities";
$res = $mysqli->query($sql1);
$facilities = array();
while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$facilities[]['id'] = $facilities_id;
$facilities[]['product_id'] = $facilities_product_id;
$facilities[]['product_current_quantity'] = $product_current_quantity;
}
$id = $mysqli->real_escape_string ($_POST['id']);
$purchase_id = $mysqli->real_escape_string( $_POST['purchase_id'] );
$facility_id = $mysqli->real_escape_string( $_POST['facility_id'] );
$product_quantity = $mysqli->real_escape_string( $_POST['product_quantity'] );
$sql1 = "UPDATE facilities
SET
`product_current_quantity` = '$product_quantity + $product_current_quantity'
WHERE $facility_id = $facilities_id AND $id = $facilities_product_id ";
$sql = "INSERT INTO purchases
(
`purchase_id`,
`facility_id`,
`product_quantity`,,
`product_id`
)
VALUES
(
'$purchase_id',
'$facility_id',
'$product_quantity',
'$id'
)";
I did some research and I think I need to use triggers. But I never work with triggers before. Any helps would be great. Thank you!
Please execute your query and better use echo statement if you have doubt in query.
use "php.net"
used this code to your updates
product_current_quantity = product_current_quantity + $product_current_quantity
how many number they can add to your product Quantity and they sum the current number.
You have used insert query and update query for the same variable $sql without any condition. If so always your following query only executes.
Then anymore no update only insertion will reflect in your table.
$sql = "INSERT INTO purchases
(
`purchase_id`,
`facility_id`,
`product_quantity`,,
`product_id`
)
VALUES
(
'$purchase_id',
'$facility_id',
'$product_quantity',
'$id'
)";

PHP/MYSQL: Multiple values using same identifying number

I am trying to write data from an invoice into 2 tables
table 1 is the invoices table
it contains:
invoice_id account sales purchase_date
then a second table invoice_items it contains the information about each line in the invoice.
id invoice_id item description quantity price amount
Basically now I am checking to see if the id exists and if it does I check if the line id exists and if it doesn't it adds the information for the invoice if the id exists it checks to see if the line id exists
$checkin = mysql_query("
SELECT `id`
FROM `invoices`
WHERE `invoices`.`id` =$invoice_id
");
if (mysql_num_rows($checkin) == 1)
{
$updatememocount ++;
mysql_query("UPDATE `invoices` SET `invoices`.`INV_ID` = '".$invid."'WHERE `invoices`.`id` =$invoice_id ") or die("load1 -" . mysql_error());
// check line id
$checklineid = mysql_query("SELECT `Line_ID` from `invoice_items` WHERE `Line_ID` = '$lineid'") or die("load1 -" . mysql_error());
if (mysql_num_rows($checklineid) == 0)
{
$insertlinecount ++;
mysql_query("INSERT INTO `invoice_items` (invoice_id, item, description, quantity, price, amount, Line_ID) VALUES ('".$invoice_id."', '".mysql_real_escape_string($row['3'])."', '".mysql_real_escape_string($row['4'])."', '".$row['9']."', '".$row['7']."', '".$row['5']."', '".$row['14']."' ) ") or die("load1 -" . mysql_error());
}
}
else
{
// makes new invoice entry and enters the line item information for the first line.
}
Data sample this is how the data comes in
Date Invoice_Id Item Description Price Amount Customer_ID Line_ID
05/12/12 1234 something whatever somthing is 15 15 2255 123
05/12/12 1234 Another_thing Whatever that is 25 25 2255 124
look this example, on duplicate key insert
<?php
$sql = "SELECT COUNT(UserID) FROM configuration WHERE UserID='SomeUser'";
$result = mysqli_query($db,$sql);
if ($result && mysqli_num_rows($result)>0) {
$aResult = mysqli_fetch_array($result);
$iRecordExists = ($aResult[0]>0?1:0);
}
if ($iRecordExists>0) {
//make the insert with another ID
}
else {
//do an insert
$sql = "INSERT INTO configuration SET someField='someValue', UserID='SomeUser'";
mysqli_query($db,$sql);
}
?>

Categories