Insert data in current table and update another table MySQL - php

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'
)";

Related

Data will not enter database

For some reason $query3 and $query4 will throw out this error
Couldn't enter data: 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 'WHERE job_id = '35' at line 1
I cannot see why it is doing this the query syntax seems fine.
Table structure:
https://imgur.com/a/ioOKZ
Actionpage7:
session_start();
require 'config.php';
$id = $_SESSION['login_user'];
$bidid = $_POST['bid_id'];
$jobid = $_POST['job_id'];
$bidder_id = $_POST['bidder_id'];
$bid_amount = $_POST['bid_amount'];
$query = " UPDATE bid SET status = '1' WHERE bid_id = '$bidid'";
$success = $conn->query($query);
$query2 = " UPDATE job SET accepted = '1' WHERE job_id = '$jobid'";
$success = $conn->query($query2);
$query3 = "INSERT into job (accepted_bidder) VALUES('" . $bidder_id . "') WHERE job_id = '$jobid'";
$success = $conn->query($query3);
$query4 = "INSERT into job (accepted_bid) VALUES('" . $bid_amount . "') WHERE job_id = '$jobid'";
$success = $conn->query($query4);
if(!$success) {
die("Couldn't enter data: " . $conn->error);
}
echo "Thank You For Contacting Us <br>";
header("location: myjobs.php");
$conn->close();
You can do it in one query:
UPDATE job SET
accepted = '1',
accepted_bidder = 'value',
accepted_bid = 'value'
WHERE job_id = '$jobid'
As stated in comments - your code is vulnerable to SQL injections. Refer to this topic to know more.
You have two types of queries here.
Query 1 and 2 are updates
$query = " UPDATE bid SET status = '1' WHERE bid_id = '$bidid'";
$query2 = " UPDATE job SET accepted = '1' WHERE job_id = '$jobid'";
They say UPDATE table and SET column = value WHERE condition is true. As the name implies this updates existing rows. The condition is used to limit the rows that the update is applied to. Without it every bid would have its status set to 1 and every job would be accepted. Which is probably not good.
Query 3 and 4 are inserts
$query3 = "INSERT into job (accepted_bidder) VALUES('" . $bidder_id . "') WHERE job_id = '$jobid'";
$query4 = "INSERT into job (accepted_bid) VALUES('" . $bid_amount . "') WHERE job_id = '$jobid'";
They say INSERT into table using (columns...) having VALUES(values...) WHERE condition. Again the name says it all, INSERT inserts new rows into the table. Now the question is what is the WHERE clause supposed to do?
Are you trying to limit the inserted rows to only those that match your condition? Well you are the one saying what rows to insert so you don't really need to do that. Are you trying to set values on the rows to be inserted? Well you can do that by adding more columns to the column list and their respective values to the value list. So it turns out there isn't really much point to a WHERE clause on an INSERT statement like that and in fact it's not allowed. That's what the error is trying to tell you.
As the other answer says you probably want to update an existing job and not insert a new one anyways.

PHP: Writing unique random number to database

I am trying to write a serial and random PIN to mysql database but some PIN values are written multiple times.
how do I skip writing $pin into pin column if it already exist?
The snippet follows:
<?php
for($serial = 1000; $serial <= 1600; $serial++) {
$serial_prefix = "HCIS";
//generate random figures.
$rand_pin1 = rand(10599, 99999);
$rand_pin2 = rand(22222, 89898);
$pin = $rand_pin1 . $rand_pin2;
$f_serial = $serial_prefix . $serial;
$check = "SELECT pin FROM pin_serial WHERE pin = '$pin'";
$check_query = mysqli_query($connection, $check);
if(mysqli_num_rows($check_query) > 0){
// how do I skip writing $pin into pin column if it already exist here
}
elseif(mysqli_num_rows($check_query) == 0){
//inserting a generated figure and $serial into serial and pin column.
$pin_serial_query = "INSERT INTO pin_serial (serial, pin) VALUES('$f_serial', '$pin')";
mysqli_query($connection, $pin_serial_query);
}
}
Create unique index for pin column:
ALTER TABLE `pin_serial` ADD UNIQUE INDEX (`pin`)
Then change your query to
INSERT INTO pin_serial (serial, pin) VALUES('$f_serial', '$pin')
ON DUPLICATE KEY UPDATE serial_pin = VALUES(serial_pin)
(note ON DUPLICATE KEY UPDATE serial_pin = VALUES(serial_pin) part, this is just example, you can just pin=pin to skip) It will update query if row with that pin value already exists, or insert a new row.
You also can use INSERT IGNORE statement, which will just ignore duplicates.
More about INSERT in MySQL docs on topic
Please note that in your example, the script is vulnerable to Sql injection attack. To avoid it, you should first pass your parameters to mysqli_real_escape_string function to make the data inside sql-safe(by escaping ambiguous characters)
A do..while loop should solve your problem:
for ( $serial = 1000; $serial <= 1600; $serial++ ) {
$serial_prefix = "HCIS";
do {
// generate random figures
$rand_pin1 = rand( 10599, 99999 );
$rand_pin2 = rand( 22222, 89898 );
$pin = $rand_pin1 . $rand_pin2;
$f_serial = $serial_prefix . $pin;
$check = "SELECT pin FROM pin_serial WHERE pin = '$pin'";
$check_query = mysqli_query( $connection, $check );
} while ( mysqli_num_rows( $check_query ) >0 );
//inserting a generated figure and $serial into serial and pin column.
$pin_serial_query = "INSERT INTO pin_serial ( serial, pin ) VALUES ( '$f_serial', '$pin' )";
mysqli_query( $connection, $pin_serial_query );
}
While this will solve your immediate issue, as the number of rows grows you'll end up sending more and more SQL requests until you find an unused PIN. You will likely be happier with the result if you allow mySQL to generate a unique PIN for each new row.
if you want to write the serial into the row where the pin generated pin already sits (effectively overwriting the old serial that is already there, you would use an UPDATE statement:
... "UPDATE pin_serial SET serial='$serial'";
If you just want to skip this pin/serial combo I think yo already got the answer. Your code should work

SQL Syntax with Updating 2nd table on 1st table insert

I am trying to issue a mysqli_multi_query, in which my querys are named $query & $query2. Query 1 is a seperate table from query 2. This is a sample of how the code syntax looks like:
$query1 = "INSERT INTO invoices (`id`,`c`) VALUES (NULL, '$client_id')";
$query2 = "UPDATE `customers` SET `a` = `$a`,`b` = `$b` WHERE `customers.id` = $client_id";
the invoices.client_id is the same as the customers.id, and I only want to update customers.id that matches the invoice client_id.
For some odd reason, everything is updated fine into my invoices, but not into my customers. Is my syntax correct?
after our discussion in the chat we figured out the following misstakes:
Your code:
$query2 = "UPDATE customers SET alarmcode = $alarmcode, garagecode = $garagecode, gatecode = $gatecode, liason = $liason, lphone = $lphone WHERE customers.id = '$client_id'";
table-def:
So the problem was not correct encapsulating of strings in the sql statement.
corrected statement was:
$query2 = "UPDATE customers SET alarmcode = '$alarmcode', garagecode = '$garagecode', gatecode = '$gatecode', liason = '$liason', lphone = '$lphone' WHERE id = $client_id";

Update query to SQL from php file

I am trying to update a patient's record its saying its complete but its not updating phpmyadmin. When I press save and update button it shows Save was successful. Any Ideas ?
<?php
include 'connect.php';
$id1 = $_POST['PatientID']; //Text box the user searches in
mysql_query("UPDATE PatientRecords SET
PatientID = '".$_POST['PatientID']."',
FirstName = '".$_POST['FirstName']."',
LastName = '".$_POST['LastName']."',
DOB = '".$_POST['DOB']."',
IDNumber1 = '".$_POST['IDNumber1']."',
Medication1 = '".$_POST['Medication1']."',
Medication1Dosage = '".$_POST['Medication1Dosage']."',
IDNumber2 = '".$_POST['IDNumber2']."',
Medication2 = '".$_POST['Medication2']."',
Medication2Dosage = '".$_POST['Medication2Dosage']."',
IDNumber3 = '".$_POST['IDNumber3']."',
Medication3 = '".$_POST['Medication3']."',
Medication3Dosage = '".$_POST['Medication3Dosage']."',
MedicalNotes = '".$_POST['MedicalNotes']."'
WHERE PatientID = '$id1');
echo"Patient Information has been updated successfully";
mysql_close($con);
?>
Your query is wrong to begin with. If you're UPDATING an existing row, leave the VALUES (... out and end the query after WHERE PatientID = '$id1'. If you're INSERTING a new row, use INSERT table (column, column, ...) VALUES (value, value, ...) and don't use WHERE.

IF-ELSE using PHP and SQL

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.

Categories