How exactly do I subtract values from a database using php? I see plenty of examples using static variables such as
<?php
$first_number = 10;
$second_number = 2;
$third_number = 3;
$sum_total = $third_number + $second_number * $first_number;
print ($sum_total);
?>
However I'm looking to subtract one database value from another, then multiply that value by another db value. To give some more detail, I have an inventory database where I'm echoing the values into a table, I'm attempting to subtract the total quantity of an item from the minimum quantity, to see how many need to be ordered, then multiply the number of parts we need to order by the cost of that part. I've dug around and found a few possible methods such as
$query = "SELECT `db`,
(`minimumquantity` - `totalquantity`) AS `quantitytoorder`
FROM `db`
WHERE id ='".$id."';"
and
<?php
$minimumquantity = $_GET['minimumquantity'];
$totalquantity = $_GET['totalquantity'];
$quantitytoorder = $minimumquantity - $totalquantity;
print ($quantitytoorder);
?>
Please before you laugh, I'm very much a beginner, can anyone point me in the right direction, or provide me with proper examples? My only real resource is the net and most examples I find are very high-level.
Field Type Null Key Default Extra
id int(3) NO PRI NULL auto_increment
partnumber varchar(20) NO NULL
description varchar(20) NO NULL
tonerprice int(20) NO NULL
totalquantity int(20) NO NULL
minimumquantity int(20) NO NULL
quantitytoorder int(20) NO NULL
replencost int(20) NO NULL
So assuming you know how to work with SQL in PHP, it's as simple as this:
// STOP USING mysql, use mysqli or PDO, for demonstration purposes only
$results = mysql_query('SELECT foo, bar, baz FROM table');
while ($row = mysql_fetch_assoc($results)) {
echo $row['foo'] - $row['bar'] * $row['baz'];
}
Assuming the columns are all numeric, that's all you need to do to subtract and multiply values from the database in PHP.
Firstly you will need to look into using mysql within php. Php has a built in class specifically created to do this. Documentation, examples and everything else a beginner needs is available here.
Secondly the query you are trying to do is possible and you are on the right tracks, try something like this:
$query = "SELECT (minimumquantity - totalquantity) AS quantitytoorder, (quantitytoorder * costofpart) AS totalcost FROM db WHERE id = '".$id."';";
My advice is to read through the mysqli documentation and do some simple examples first to get familiar with it - then you should try and complete your own task.
Try this query
SELECT (value2-value1) as minimumquantity,((value1 + value2)* value3)
as totalquantity FROM table WHERE id = '".$id."';";
Related
I have a table in database as followings:
locationname postcode locationlatitude locationlongitude
--------------------------------------------------------
1. gsfs 2322. 352353. 35235235
2. gsfs 2322. 352443. 352353
3. gsfs 2322. 352353. 35235235
.
.
I want to calculate the distance between each location to all locations in the table(many to many). I have been able to compute one-to-many and one-to-one calculation but I couldn't figure out how to calculate distance from every location to every location. Do I have to use nested loop or not? Should I have to fetch all the data into an array first? Can you please help me out with this. I don't know whether my question is clear or not.
I have tried but I couldn't execute it due to errors and stupid mistakes.
$sql = "SELECT id, locationname, locationlatitude, locationlongitude, postcode FROM distancetable";
$result = $conn->query($sql);
$i=0;
$j=0;
while($row = mysql_fetch_assoc($result)) {
for ($row=0; $row <num_rows ; $row++) {
$lat1=$row[$i]["locationlatitude"];
$long1=$row[$i]["locationlongitude"];
$suburb1=$row[$i]["locationname"];
$lat2=$row[$j]["locationlatitude"];
$long2=$row[$j]["locationlongitude"];
$suburb2=$row[$j]["locationname"];
$distance=Round(ACOS(SIN(PI()*$long1/180)*SIN(PI()*$long2/180)+COS(PI()*$long1/180)*COS(PI()*$long2/180)*COS(PI()*$lat1/180-PI()*$lat2/180))*6371,3);
echo nl2br (" \n ");
echo $row[id]. ". Distance between " .$suburb1. " to " .$suburb2. "=" .$distance;
$i++;
$j++;
So I made a table like this:
create table latlongdata (
id int auto_increment primary key not null,
locationname varchar(35) not null,
postcode char(5) not null,
locationlatitude numeric(6, 3) not null,
locationlongitude numeric(6,3) not null
);
then I added some sample lat/long values like so:
insert into latlongdata (locationname, postcode, locationlatitude, locationlongitude)
VALUES
('Fenwick, MI', '48834',43.142,-85.049),
('Andover, MN', '55304', 45.255, -93.287),
('Minneapolis, MN', '55422', 45.015, -93.340),
('Lydia, SC', '29079', 34.296, -81.113);
then I made a query like so:
select
a.postcode as FromPostCode,
b.postcode as ToPostCode,
round(acos(sin(pi()*a.locationlongitude/180)*sin(pi()*b.locationlongitude/180)+cos(pi()*b.locationlongitude/180)*cos(pi()*a.locationlatitude/180-pi()*b.locationlatitude/180))*6731, 3) as distance
from latlongdata a
inner join latlongdata b
where b.id > a.id;
...which should be close to what you want, but I think there might be something wrong with your math since the results didn't make a lot of sense. But that should be how you do it.
Note the self-join with the inequality operator on the SELECT statement. This will prevent you from calculating B -> A after you've already calculated A -> B. Fair warning: With a large table, you should expect the result set for this to be... large. It might be better to directly insert the results into a new table (assuming you have sufficient storage space) than try to select out the results.
I want to fetch some info from my database, and choose which of the info in the string, I want to display.
--- What I know so far ---
This code is showing me NULL value:
$ticketis = mysql_query("SELECT `module` FROM games ORDER BY `id` DESC LIMIT 1,1");
$showticket = mysql_fetch_assoc($ticketis);
$rest = mb_substr($showticket,0,30);
var_dump($rest);
AND this code is showing me the data-string I want to cut out specific data from:
$ticketis = mysql_query("SELECT `module` FROM games ORDER BY `id` DESC LIMIT 1,1");
$showticket = mysql_fetch_assoc($ticketis);
var_dump($showticket);
This is the return value of the above code:
array(1) { ["module"]=> string(11) "0.435264836" }
What I want is to cut out is the numbers and display these: 0.435264836
Anyone got a clue what I can do to make that happen?
Thank you!
Use this $showticket['module']
mysql_fetch_assoc returns an array, not just a single value. Since you're using mysql_fetch_assoc you get an associative array indexed by the column name, hence the ['module']. If you would use mysql_fetch_row you'd get a numeric index and thus have to use $showticket[0].
But please don't forget that all the mysql_* functions are deprecated and will be removed in future versions of PHP!
Thanks for your help. It seemed I had to use print_r to get the pure numbers from the string. My code ended up like this, combining Remo and FirstOne's suggestions. Thanks.
$ticketis = mysql_query("SELECT `module` FROM games ORDER BY `id` DESC LIMIT 1,1");
$showticket = mysql_fetch_assoc($ticketis);
print_r($showticket['module']);
I have a table where I need to find wheter the cell is empty or not.
I don't have the specific column name so I need to display all of the cells that are not empty. (PHP solution would fit too.) Thank you!
Here is my piece of code:
$result1 = mysql_query("SELECT * FROM `FACILITIES` WHERE `room_id` = '{$row['id']}'");
while($row1 = mysql_fetch_assoc($result1)) {
if(empty($row[''])) { //What should I fill in in the $row variable?
alert("Empty");
}
}
I have tried doing in in PHP, but a MYSQL solution would fit too.
You should prevent that problem in the first place. Handle that on DB design level. If you want all your records having values in every column, then define the columns so: not null.
a simple sql that you can rewrite and use would be similar...
sqlfiddle
select * from t where
(col1 is null or col1='')
or
(col2 is null or col2='')
;
sqlfiddle
I have some mysql tables (one for each container) like so (the table would be called containerA for instance):
Box_ID Box_Name Box_Distributor Container Box_state
======---========---===============---==========----=========
1 Box 1 Delivery Comp.1 ContainerA Full
2 Box 2 Delivery Comp.2 ContainerA Empty
3 Box 3 NULL ContainerA Missing
and I have another mysql table with a list of containers:
container_id container_name
============---==============
1 A
2 B
and I want to report the name of the container and the number of empty boxes to a webpage.
I've written this to do it:
$v1 = 0;
$sql = "select * from containers";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$containers[] = $row[container_name];
$containerid[] = $row[container_id];
}
while ($v1 < 14)
{
$containerend = $containers[$v1];
$containerstart = "container";
$containername = $containerstart.$containerend;
$sql = "SELECT COUNT(*) FROM `$containername` WHERE state = 'Empty';";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_fetch_array($result);
var_dump($containers[$v1]);
var_dump($count[$v1]);
$v2 = $v1 + 1;
$v1 = $v2;
}
Which works in listing the container names, but it only gives me the first result for the empty boxes, the rest of the array is returned as NULL:
string(1) "4" NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
Am I doing something stupid here? Surely the SQL query in the while loop should be returning the count for each container?
Any help is appreciated.
change this
while ($row = mysql_fetch_array($result))
{
$containers[] = $row[container_name];
$containerid[] = $row[container_id];
}
to
while ($row = mysql_fetch_array($result))
{
$containers[] = $row['container_name'];
$containerid[] = $row['container_id'];
}
you missed '.
Am I doing something stupid here?
Yes.
Splitting the same data across multiple tables is really dumb.
$sql = "select * from containers";
...
while ($v1 < 14)
{
...
$sql = "SELECT COUNT(*) FROM `$containername` WHERE state = 'Empty';";
Relational database management systems are very good at performing joins. Procedural / OO languages are NOT.
If all your containerX tables where in a single table then the performance would be a lot better and the code much simpler. And it's trivial to create views named like the individual tables on an aggregated table thus avoiding having to rewrite most of your code straight away.
Why are you fetching all the containers then only processing the first 14?
What is $v2 doing?
It's rather hard to work out why your code is misbehaving as your description doesn't match your code - your query states "WHERE state = 'Empty'" but your table description has no column named state (and if that were an accurate report, then the code would stop on the first iteration with a MySQL error message).
$count is in essence only a single value (as you are counting a single container), so it will work for the first element, but not for subsequent elements. Quick fix is to use mysql_result:
$count = mysql_result($result, 0);
as ever, this code is using mysql functions that are both insecure and due to be deprecated - do consider switching to mysqli or pdo.
Here is my code
if (isset($_GET["range"])) { $range = $_GET["range"]; } else { $range = BLOB; }
Basically, I'm using the GET variable to search a table under the column 'range'. Only problem is, in the case that range is not set I would like a default variable that could return all the products.
I'm doing this so I can avoid including multiple SQL queries. Mind you, the part of the code I'm trying to replace is BLOB. Any thoughts?
EDIT: If you're going to vote down my question, at least have the decency to comment why.
You're asking 'I have a place where I put a piece of data to use as a filter (the name of a clothing range) to limit the returns on my search. If I don't pick a specific clothing range, what can I put in that filter?'
SQL has a data value to indicate 'I have no meaningful data in this field': NULL.
You have no meaningful information on what clothing range you would like to filter on, so one possible method for handling this would be to pass in a NULL for range, and then have the SQL side process that parameter with a range_variable = range_column OR range_variable IS NULL
Here's a quick and dirty example so you can see how it works:
create table clothing (range varchar (20))
insert into clothing
select 'Value1'
union select 'value2'
union select 'value3'
select * from clothing
declare #range_var varchar(20)
set #range_var = 'value2'
select * from clothing
where range = #range_var or #range_var is null
set #range_var = NULL
select * from clothing
where range = #range_var or #range_var is null
GO
drop table clothing
I would like to comment, but I can't, because of my reputation, so I'll try to answer the question as I understand it.
If your query ends with something like (no matter the correct syntax) :
LIMIT 0, $range
Try something like
<?php
if(isset($_GET['range']) && is_int($_GET['range']))
$range = ' LIMIT 0, '.$_GET['range'];
else
$range = '';
Or in just one line
<?php
$range = (isset($_GET['range']) && is_int($_GET['range'])) ? ' LIMIT 0, '.$_GET['range'] : '';
I hope I'm not off base...