mySQL seperate data stored in table - php

currently I have two pieces of data being stored in a sql db and then pulled into my website. What I want though is the two pieces of data being stored to be separated instead of totaled together.
So i setup my DB like so:
DROP TABLE IF EXISTS totals;
CREATE TABLE totals (
id int(11) NOT NULL AUTO_INCREMENT,
total float NOT NULL,
PRIMARY KEY (id)
) ;
INSERT INTO totals VALUES (1, 0);
And the PHP I'm using:
$api = array();
$api[] = 'http://api.jo.je/justgiving/data/myuserpage';
$api[] = 'http://api.jo.je/justgiving/data/myuserpage2';
$total = 0;
foreach($api as $data) {
$open = file_get_contents($data);
$feed = json_decode($open);
if(is_object($feed)) {
$total = $total + $feed->donations_total;
}
}
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); // new data
$id = 1;
// query
$sql = "SELECT total
from totals
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($id));
$data = $q->fetch();
$total = $data['total'];
Being a noobie at this, I just need some help storing two seperate pieces of data instead of one.

I think you simply want two separate columns in the table:
CREATE TABLE totals (
id int(11) NOT NULL AUTO_INCREMENT,
total1 float NOT NULL,
total2 float NOT NULL,
PRIMARY KEY (id)
) ;
$api = array(
'total1' => 'http://api.jo.je/justgiving/data/myuserpage',
'total2' => 'http://api.jo.je/justgiving/data/myuserpage2',
);
// The saving part is missing from your code, but it should be something like
$sql = "UPDATE totals SET {$source}=? WHERE id=?";$q = $conn->prepare($sql);
$query = $conn->prepare($sql);
// Note: the above assumes that the "id" already exists. Otherwise
// you need an "UPSERT" (UPdate or inSERT) that will insert a new value or update
// it if it already exists. Find more # this answer:
// https://stackoverflow.com/questions/15383852/sql-if-exists-update-else-insert-into
/*
* Instead of adding up the two API calls' results, we store them separately
*
* Of course the value of "id" here must be the same as in the second page, or
* what you will retrieve will NOT be what you have stored!
*/
foreach($api as $column => $source) {
$data = file_get_contents($source);
$feed = json_decode($data);
if (is_object($feed)) {
$value = $feed->donations_total;
$query->execute(array($value, $id));
}
}
Now in the second page
// query
$sql = "SELECT total1, total2 from totals WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($id));
$data = $q->fetch();
$total1 = $data['total1'];
$total2 = $data['total2'];
(This is the link to the answer referred above).

Related

how to set different values for id column of several tables

I need to update id column of several tables with php uniqid() values
after running this code - all rows inside each table has the same value
how to set different value for each row ?
$arr = ['lorem', 'ipsum', 'dolor']; // table names
foreach($arr as $tb){
$st = $db-> prepare("select * from " . $tb);
$st -> execute();
$arrb = $st->fetchAll();
foreach($arrb as $elb){
$id = uniqid();
$sqb = "update " . $tb . " set id = :aid";
$stb = $db->prepare($sqb);
$stb->execute([":aid" => $id]);
}
}
As already pointed out by Amitesh, your code is setting the same uniqid() value to all rows in each table multiple times. Furthermore, you are preparing the same sql statement for each row, missing one of the important benefits of using prepared statements.
$arr = ['lorem', 'ipsum', 'dolor']; // table names
foreach($arr as $tb){
/*
* assign temporary UUID (requires CHAR(36)) to all rows if there
* is no other way of uniquely identifying the rows
*/
$db->query("UPDATE {$tb} SET id = UUID()");
$st = $db->prepare('select id from ' . $tb);
$st->execute();
$arrb = $st->fetchAll();
// prepare once per table
$sqb = "update $tb set id = :aid where id = :old_id";
$stb = $db->prepare($sqb);
foreach($arrb as $elb){
// execute once per row
$stb->execute([':aid' => uniqid(), ':old_id' => $elb['id']]);
}
}

Get column value from a foreign key reference in PHP

My output is only id column, reference to "combustibili" table. How to get value reference from combustibili?
$combustibili = "SELECT * FROM tabelint";
$rezcom = $conectare->query($combustibili);
$p = new GNUPlot();
while($row = $rezcom->fetch_assoc()) {
if($row["ID"] == 1){
$data = new PGData($row["ID_BENZINA_STANDARD"]);
$data2 = new PGData($row["ID_MOTORINA_STANDARD"]);
$data3 = new PGData($row["ID_BENZINA_SUPERIOARA"]);
$data4 = new PGData($row["ID_MOTORINA_SUPERIOARA"]);
}
}
From information provided assume COMBUSTIBILItable structure should be something like
COMBUSTIBILI(id pk and fk_in_tabelint number, name varchar, price float)
TABELINT(id pk number, ID_BENZINA_STANDARD fk->COMBUSTIBILI number ... etc)
so
SELECT * FROM tabelint where id=1 will retun something like
(id #1, ID_BENZINA_STANDARD #2 ... etc)
and just need to query COMBUSTIBILI with fks
$combustibili = "SELECT * FROM tabelint";
$rezcom = $conectare->query($combustibili);
$p = new GNUPlot();
//assume also record for id=1 exists
while($row = $rezcom->fetch_assoc()) {
if($row["ID"] == 1){
$data = new PGData($row["ID_BENZINA_STANDARD"]);
$data2 = new PGData($row["ID_MOTORINA_STANDARD"]);
$data3 = new PGData($row["ID_BENZINA_SUPERIOARA"]);
$data4 = new PGData($row["ID_MOTORINA_SUPERIOARA"]);
}
}
//add for each id_s
//BENZINA_STANDARD :: should be 1 row if db is consistent
//not sure how PGData class is defined and how to retrive only id : maybe $pgd->id ...
//$data = $row["ID_BENZINA_STANDARD"] : this is what is needed
$sql = "SELECT * FROM COMBUSTIBILI where id=".$data;
$sqlout = $conectare->query($sql);
//just parse and retrive what ever wanted
while($row = $sqlout->fetch_assoc()) { ... etc ... }
//same with data2_3_4

I want in this code please to increase the quantity of same item when insert without add new record to the table

I want in this code please to increase the quantity of the same item when inserting
without adding a new record to the table.
the insert working is done, but please I need when inserting to the table that
contains a unique number of the invoice to increase the number of items without
duplicate records.
<?php
session_start();
include('../connect.php');
$a = $_POST['invoice'];
$b = $_POST['product_id'];
$c = $_POST['qty'];
$saleproduct = $_POST['saleproduct'];
$w = $_POST['pt'];
$amount = $_POST['amount'];
$dateok = $_POST['dateok'];
$result = $db->prepare("SELECT * FROM products WHERE product_id= :userid");
$result->bindParam(':userid', $b);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
$sellprice=$row['price'];
$prodcode=$row['prod_code'];
$code=$row['product_code'];
$color=$row['color_name'];
$size=$row['size_name'];
$sizenum=$row['note'];
$name=$row['product_name'];
}
$sql = "UPDATE products
SET qty=qty-?
WHERE product_id=?";
$q = $db->prepare($sql);
$q->execute(array($c,$b));
$grandtotal = $sellprice- $saleproduct ;
$d=$grandtotal*$c;
$sql = "INSERT INTO sales_order
(invoice_number,prod_code,product_id,qty,amount,saleproduct,name,color_name,size_name,note,price,product_code,date,dateok) VALUES
(:a,:prodcode,:b,:c,:d,:saleproduct,:e,:ee,:eee,:sizenum,:sellp,:i,:k,:kok)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':prodcode'=>$prodcode,':b'=>$b,':c'=>$c,':d'=>$d,':saleproduct'=>$saleproduct,':e'=>$name,':ee'=>$color,':eee'=>$size,':sizenum'=>$sizenum,':sellp'=>$sellprice,':i'=>$code,':k'=>$date,':kok'=>$dateok));
?>
You'll need to run UPDATE query to update quantity of the existing record i.e.:
UPDATE `sales_order` SET `qty` = `qty` + 1 WHERE `id` = ?
You will obviously have to bind id of the desired record within sales_order table.

how to update column without using auto_increment value with 001 to so on

This is my table with name and unique numberenter image description here
This is my PHP code
$id = explode(",", $params["txtID"]);
for ($i = 0; $i <count($id); $i++) {
$sql = "SELECT 'auto_increment' as LastID FROM
INFORMATION_SCHEMA.TABLES WHERE table_name = 'esi_master' ";
$result = $this->con->query($sql);
if (intval($result->rowCount($result)) > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$lclId = intval($row["LastID"]) - 1 + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
} else {
$lclId = intval($row["LastID"]) + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
$sql = $this->con->prepare("UPDATE esi_master SET esi_status = 1,
esi_dcno = '$lclDcno[$i]' Where esi_id = '$id[$i]'");
echo $result = $sql->execute();
}
Here First I insert Names to the table using Insert Statements and next for some operation I update the Unique number unique number should start updating from the empty row, update done with unique id, The txtID contains ID`s like 1, 2, 3, 4 so on as I select table row in front end, in that basis that updates.Thanks in Advance.
You need another field to save, with type varchar(10).
data will not be able to save into integer(auto_increment)

Need to figure out total hours between check-in and check-out times

I am trying to create a check-in/check-out table in my database. My check-in form works without issue, inserting the time into my database. The problem occurs when I try to check out. Everything is good on the first entry...
But when I try to check in and check out again, this happens...
So far so good, but when I check out...
Currently, my code updates the out column and totalTime column of all matching child_id's.
Here is my code:
// Select the correct child from the database
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$var = $row['id'];
// Insert the check out time for the child
$query = "UPDATE checkinout
SET `out` = :nowTime
WHERE child_id = $var
AND `in` IS NOT NULL";
$statement = $pdo->prepare($query);
$statement->bindValue(':nowTime', date("YmjHis"));
$statement->execute();
// Select check in time for specified child
$sql_inTime = "SELECT `in` FROM checkinout
WHERE child_id = $var";
$inResult = $pdo->query($sql_inTime);
$inRow = $inResult->fetch();
$inTime = strtotime($inRow['in']);
// Select the check out time for specified child
$sql_outTime = "SELECT `out` FROM checkinout
WHERE child_id = $var";
$outResult = $pdo->query($sql_outTime);
$outRow = $outResult->fetch();
$outTime = strtotime($outRow['out']);
// Find total hours
$totalTime = abs($outTime - $inTime)/(60*60);
// Update totalHours column for specified child
$queryTotalTime = "UPDATE checkinout
SET totalTime = :totalTime
WHERE child_id = $var
AND 'out' IS NOT NULL";
$statement = $pdo->prepare($queryTotalTime);
$statement->bindValue(':totalTime', $totalTime);
$statement->execute();
I think you could do all of this in your first update statement using TIMESTAMPDIFF rather than figuring the total time with PHP:
UPDATE checkinout
SET
out = NOW(),
totalTime = TIMESTAMPDIFF(SECOND, `in`, NOW()) / 3600
WHERE
child_id = $var
AND out IS NULL
The criteria WHERE out IS NULL will only update rows that do not have a value in the out column yet.
IF you have MySQL Db THEN sql will be
SELECT TIMESTAMPDIFF(HOUR,in,out) from checkinout;

Categories