PHP/MYSQL: Multiple values using same identifying number - php

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);
}
?>

Related

How to get columns values after insert using php mysql?

In this code, after insert values to DB.I am doing select query for selecting invoiceNo($sql1= "select invoiceNo from invoices order by invoiceID desc limit 1"; ).Instead of selecting from DB how to get InvoiceNo?
For eg: Assume two users are there.Two users inserts InvoiceID at a same time.While doing "select invoiceNo from invoices order by invoiceID desc limit 1";this will get last coming invoiceID .I need to get specific invoiceID (for particular user) .How to get it?
$query = "select * from invoices order by invoiceID desc limit 1";
$result = $link->query($query);
$row = $result->fetch_assoc();
$invoiceNo = $row["invoiceNo"];
$getinvoiceNo = str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT); //inserting like 0000
$sql = "INSERT INTO invoices (invoiceNo)
VALUES ('$getinvoiceNo')";
if ($link->query($sql) === TRUE) {
//echo "1";
$sql1 = "select invoiceNo from invoices order by invoiceID desc limit 1";
$last_id = mysqli_insert_id($link, $sql1);
$result1 = mysqli_query($link, $sql1);
$row1 = mysqli_fetch_array($result1);
echo json_encode($row1);
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysql_close($link);
If i understand your question correctly, you are concerned about possible data corruption from the concurrent update of the record.
I think you should give a look to mysql SELECT ... FOR UPDATE syntax, it should do what you ask: lock the selected row until an update is fired. Then the lock will be released.
For example:
SELECT table_field FROM table_name WHERE table_id_field = id_param FOR UPDATE
will lock the selected row until
UPDATE table_name SET table_field = table_field + 1 WHERE table_id_field = id_param
If you're looking to prevent collisions in invoice numbers, all you need to do is create your table as
CREATE TABLE invoices (
invoiceID INTEGER NOT NULL AUTO_INCREMENT,
other columns . . .
PRIMARY KEY (invoiceID)
);
Then when you do your INSERT, don't insert the invoiceID and let MySQL do it.
This will ensure that each new invoice has a unique invoiceID.

How to loop for every value in table AND find average

I am a beginner programmer and I am trying to find the average user rating of vendor 2.
My steps are as follows:
1. User 'Jimmy' gives a rating of 3 to vendor 2 (ratings are out of 5)
2.TABLE vendoratings is updated
3. ratingstot.php then calculates the total sum of ratings and the number of responses for ALL vendors before updating TABLE vendortotalratings shown below
4.User 'Jimmy' clicks on 'View average user rating'
5. The values totalratings and totalno are retrieved and divided in Javascript
var average= totalratings/totalno
6. totalno is displayed to user Jimmy. END
Question
1. I need help forming the for or while loop in ratingstot.php to calculate both ratings and no. of responses belonging to vendor X before inserting them in vendortotalratings table for every vendor.
ratingstot.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
//Database connection
$conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");
//Unsure how to loop this to make vendor new value every loop
for($i=0; $i<=6; $i++){
$vendor = ??
//Calculate sum of ratings from table ratings
$result = $conn->query("SELECT SUM(ratings) FROM ratings WHERE vendorid = '".$vendorid."' ");
$row = mysqli_fetch_array($result);
$totalratings = $row[0];
//Calculate no. of responses (by counting no. of rows)
$result1 = $conn->query("SELECT * FROM ratings WHERE vendorid = '" . $vendorid."' ");
$totalno = mysqli_num_rows($result);
//inserting the results into the table
$query = " UPDATE vendortotalratings SET ";
$query .= " totalratings = '". $totalratings ."', totalno='".$totalno."' ";
$query .= " WHERE vendorid = '". $vendorid ."'";
$result2 = $conn->query($query);
}
echo($outp);
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
I have no idea how to loop this, are there any easier steps to calculate average of ratings for each vendors?
Instead of all these complicated things, you can simplify the required solution like this:
(Assumption: I'm assuming that vendorid, ratings, totalratings and totalno columns are of type INT)
Use the below statement/query to get the totalratings and totalno corresponding to each vendorid.
$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
Now loop through the $result result set using while() loop.
while($row = $result->fetch_array()){
...
}
In each iteration of above while() loop, check if the vendorid value already exists or not. If it exists, then UPDATE the row with new totalratings and totalno, otherwise INSERT a new row comprising of vendorid, totalratings and totalno.
while($row = $result->fetch_array()){
$res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
if($res->num_rows){
// Update the existing row
$conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
echo "Affected rows: " . $conn->affected_rows . '<br />';
}else{
// Insert a new row
$res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
if($res) echo "New row inserted <br />";
}
}
So the complete code of try-catch block would be like this:
// your code
try{
//Database connection
$conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");
$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
while($row = $result->fetch_array()){
$res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
if($res->num_rows){
// Update the existing row
$conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
echo "Affected rows: " . $conn->affected_rows . '<br />';
}else{
// Insert a new row
$res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
if($res) echo "New row inserted <br />";
}
}
}catch(Exception $e) {
$json_out = json_encode(array("result"=>0));
echo $json_out;
}
The question doesn't clarify how the records are first inserted in vendortotalratings table. So, assuming that there is already a record in this table for each vendor, you don't have to write a whole new loop.
Updating vendortotalratings:
SQL can take care of calculating the total ratings and their counts in a single query which can then replace the loop that you have.
UPDATE vendortotalratings vtr
INNER JOIN
(
SELECT vendorid, SUM(ratings) AS sumratings, COUNT(ratings) AS countratings
FROM vendoratings
GROUP BY vendorid
) vr
ON vtr.vendorid = vr.vendorid
SET
vtr.totalratings = vtr.totalratings + vr.sumratings
,vtr.totalno = vtr.totalno + vr.countratings
Computing averages:
As for your second question, to compute the average, you could run the following query which will give you the run-time result:
SELECT vendorid, totalratings, totalno,
CAST((totalratings/totalno) AS DECIMAL(10, 2)) AS avgrating
FROM vendortotalratings;
The variable avgrating can be accessed directly in PHP by using $row['avgrating'] if you're fetching an associative array from the results, or by using the appropriate index number, which in this case should be $row[3]

php sql UPDATE with nested FROM (SELECT)

After hours of trying I need your advice.
I want to combine rows from 2 tables.
After I created a new row in table1 I want to find a row in table2 and combine some of the fields.
If I put the nested SELECT in the SET function
(SET postcode=(SELECT etc)
is works, but if I put it in the FROM function is gives an Error that the syntax is wrong
my code:
$sql = "INSERT INTO instanties(institution, category, postcode)
VALUES('$emapData[0]', '$emapData[1]', '$emapData[2]')";
if ($conn->query($sql) === TRUE) {
//get last added id
$last = $conn->insert_id;
//define WHERE function
$where="postcode_id=$postcode_id AND (minnumber <= $number AND maxnumber >= $number)";
//UPDATE last added row in table with info from other table
$sql2 = "UPDATE instanties
SET postcode_id=pc.postcode_id
FROM
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
) pc
WHERE id=$last";
$result = $conn->query($sql2);
if ($result) {
echo 'update is done<br/><br/>';
}
}
else {
echo "Error: " . $sql2 . "<br>" . $conn->error.'<br/><br/>';
}
}
else {
echo "Error: " . $sql . "<br>" . $conn->error.'<br/><br/>';
}
That's not a valid MySQL syntax. You cannot add a "FROM" clause to an UPDATE statement.
http://dev.mysql.com/doc/refman/5.0/en/update.html
However, what you want to accomplish is still possible this way:
$sql2 = "UPDATE instanties
SET postcode_id=
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
)
WHERE id=$last";
As long as there is only 1 result from the nested SELECT (and your LIMIT 1 kinda does that).
EDIT:
If you need many fields from the postcode table, you can join on it:
$sql2 = "UPDATE instanties as i
JOIN (
SELECT *
FROM postcode
WHERE $where LIMIT 1
) as pc
SET i.postcode_id=pc.postcode_id
WHERE i.id=$last";
We would usually use an "ON" clause with the join, but since you're only updating 1 row and your nested SELECT will also only return 1 row, it's not necessary.
try this:
$sql2 = "UPDATE instanties
SET postcode_id=(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1)
WHERE id=$last";

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.

How to UPDATE a column using an array

I have a table whose primary key is a column named St_ID. I want to update another column in that same (ID) using values stored in an array. But when I try the code below, the result is a new record with an St_ID value of '0' and all other columns are empty.
Note, courseID is a value chosen through a drop down list. Do you have any idea where I went wrong?
for ($i = 0; $i < $count; $i++){
$Student = $foo[$i];
$res = mysql_query("SELECT St_ID FROM student WHERE St_ID='$Student' ");
while($row = mysql_fetch_array($res))
{
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
}
}
if (!mysql_query($sql,$connectdb))
{
die ('Error :'.mysql_error());
}
echo "The Students are add to the course <br />";
Here simplified code, with only one query
$where = "'".implode("','", $foo)."'";
$res = mysql_query("UPDATE student set ID = courseID WHERE St_ID IN ($where)")
or die('Error :'.mysql_error());
echo "The Students are add to the course <br />";
you select St_ID but try to insert courseID
in this line
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
SELECT St_ID FROM student WHERE St_ID='$Student'
INSERT INTO student (ID) VALUES ...
If you want to update that record you chose, you must use the UPDATE sql command instead;
UPDATE student
SET ID=...
WHERE St_ID='$Student'

Categories