PHP MySQL WHERE SUM WHERE SUBSTRING - php

I do not understand something! I want to create a query ... in the database under the following entry field stamp_updated, 2014-01-28 17:31:02.
Now I just want to have records with the tag 28:
$ qry = "SELECT SUM (bytes) AS total FROM acct_v4 WHERE SUBSTRING (stamp_updated, 9,10) = '28 '";
Unfortunately, I get no output, it's the SUBSTRING?
PS:
What is supposed to be: I logged the port traffic, let him write in a database and would like to have daily statistics.
done ask new
Now I stand in front of logig proplem ... how do I put it best when I try to spend as Everyday Traffic?
2014-01-26: xx traffic 2014-01-27: xx traffic 2014-01-28: xx traffic
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<?php
function formatBytes($size, $precision = 2)
{
$base = log($size) / log(1024);
$suffixes = array('', 'k', 'MB', 'GB', 'TB');
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
$db=mysql_connect("localhost","traffic",".....");
mysql_select_db("traffic",$db);
$qry = "SELECT SUM(bytes) AS total FROM acct_v4
WHERE SUBSTRING(stamp_updated,9,2) = '28' ";
$select = mysql_query($qry);
$result = mysql_fetch_array($select);
echo 'Summe: '.formatBytes($result['total']);
//echo $result['total'];
?>

You can try
SELECT SUM (bytes) AS total FROM acct_v4 WHERE DAY(stamp_updated) = 28;

your SUBSTRING (stamp_updated, 9,10) will return 10 charcters after the position 9
--> 28 17:31:0
this is the basic of SUBSTRING
SUBSTRING(str, pos, len)
so in your case you should just change 10 to 2 like that
SUBSTRING (stamp_updated, 9,2)
and it will work
your whole query will be
$ qry = "SELECT SUM(bytes) AS total FROM acct_v4
WHERE SUBSTRING(stamp_updated,9,2) = '28' ";

Without seeing your SHOW CREATE TABLE, it looks as though you are after dates with 28 for the day. You should use MySQL's DAY function. This assumes that stamp_updated is a proper DATE or DATETIME field.
$qry = "SELECT SUM (bytes) AS total FROM acct_v4 WHERE DAY(stamp_updated) = 28";

Related

PHP and ordering persons randomly but always in same order when using same data

I'm using PHP. My target is to order persons who have same total points. When points are 75, the order needs to be same every time when the script is executed. When points are 80 or something else, the order has to change, but it needs to be same every time when the script is executed and total points are 80.
User ID 258 = Milla
User ID 289 = E-P
User ID 290 = Jari
User ID 449 = Pepe
User ID 633 = Elias
User ID 634 = Virpi
User ID 635 = Jaakko
User ID 636 = Joona
Let's say that the total points are 75.
$total = 75;
# $user_id[0] means first number of $user_id
# for example: if $user_id is 634, then $user_id[0] = 6
$count = $user_id[0] . ($user_id % 2) . ($user_id * 0.33);
$number = bcdiv("$total", "$count", 16);
list($temp, $number) = explode(".", "$number");
$number = ($number % $user_id) . $number;
When I use this code for every person and order them by $number which is a string, the descending order will be this:
E-P
Joona
Elias
Jari
Jaakko
Pepe
Milla
Virpi
I want the script be as fair as possible. I mean that if a person has, for example, high user ID, he should not be treated better with all total points than a person whose user ID is lower.
What do you think? Should I improve the code? Or are everybody on the same line and treated equally when the total points will be changed?
Oh yeah, one more thing. The script needs to run as quickly as possible. If you have ideas, please feel free to tell me.
Update
I ended up using this kind of code:
$total = 75;
$user_id = 258;
$count = $user_id * 0.33;
$number = bcdiv("$total", "$count", 16);
list($temp, $number) = explode(".", "$number");
$number[0] = $number[10]; # get 10th number to 1st number
If there are ways to optimize it, I would like to hear. Thanks.
If you seed the random number generator, then the randomness will be the same based on the seed. This will always generate the same shuffled array:
$total = 75;
srand($total);
shuffle($user_id);
Then if you set $total = 80 you will get a different shuffled array, but it will always be the same when $total = 80.

PHP - Changing Value by a small market percentage

First post, please be gentle.
I'm trying to create a simple market script where for example I have a number in my database ie 50.00 and I want to run a cron job php script to increase or decrease this randomly to a minimum of 10.00 and a maximum of 75.00.
I thought a random 0,1 follow by 2 if statements 1 rand(-0.01,0.05) if 2 rand(0.01,0.05) then $sql = "UPDATE price SET oil='RESULT'";
I've tried a few times at the above but I can't get it to run and the other crons in the file work.
<?php
//Get Oil Price from database
$oilchange = rand(1, 2);
if ($oilchange == '1') {
$oilnew = rand(0.01,0.05);
//Oil price from database times oil new.
} else {
$oilnew = rand(-0.01,-0.05);
//Oil price from database times oil new.
}
// Update Price
?>
Rand is for integers (whole numbers)
First up, your use of rand between two decimal values (called floats) won't work, as rand is for integers only. So, you'd first want to have a random function which does output floats, like this:
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
Then we can safely use it between, say, 1% and 5%:
$percentSwing = randomFloat(0.01, 0.05);
Rand defaults to being 0 or 1. We can use that to randomly invert it, so we also cover -1% to -5%:
$percentSwing *= rand() ? 1 : -1;
The above could also be written like this:
if(rand() == 1){
// Do nothing:
$percentSwing *= 1;
}else{
// Invert it:
$percentSwing *= -1;
}
So, we now know how much we need to swing the number by. Let's say it was $oilPrice:
$oilPrice = 48;
We can just multiply the percent swing by that number to get the amount it's changing by, then add it back on:
$oilPrice += $percentSwing * $oilPrice;
So far so good! Now we need to make sure the price did not go out of our fixed range of 10 to 75. Assuming you want to 'clamp' the number - that means if it goes below 10, it's set at 10 and vice-versa, that's done like this:
if( $oilPrice < 10 ){
// It went below 10 - clamp it:
$oilPrice = 10;
}else if( $oilPrice > 75 ){
// It went above 75 - clamp it:
$oilPrice = 75;
}
The above can also be represented in one line, like this:
$oilPrice = max(10, min(75, $oilPrice));
So, that gives us the whole thing:
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
// Define the oil price (e.g. pull from your database):
$oilPrice = 48;
// get a random 1% to 5% swing:
$percentSwing = randomFloat(0.01, 0.05);
// Invert it 50% of the time:
$percentSwing *= rand() ? 1 : -1;
// Swing the price now:
$oilPrice += $percentSwing * $oilPrice;
// Clamp it:
$oilPrice = max(10, min(75, $oilPrice));
// Output something!
echo $oilPrice;
As a side note here, money in real financial systems is never stored as a float, because rounding errors can cause major problems.

PHP - Simple Subtraction Doesn't Add Up

I have no idea why this simple mathematical equation doesn't work. It's making me crazy - am I blind? Instead of subtracting $number from $Amount2 it produces a negative number. So if $Amount2 starts with a value of 100 and $number is a value of 10 I get -10 instead of 90 as the result.
//find how much green they are holding
$resultto = db_query("SELECT * FROM Users_Panickles WHERE PSID ='$PSID'");
$rowgifter = db_fetch_array($resultgifter);//fetch the name of the giftee character
$Amount2 = $resultgifter["Amount"];
//now alter the accounts
$Amount2 = $Amount2 - $number; //subtract the gift from the gifter's account and update the record
db_query ("UPDATE Users_Panickles SET Amount='$Amount2' WHERE PSID = '$PSID'");

PHP rounding issue

I am getting a rounding issues, I have a database of 3 charities with different amounts.. then in the front I have the 3 charities displaying there percentage based on the amount assigned to them and the total percentage always needs to add to 100%.. currently if each charity has 1 assigned to it, it displays 33% on each which equals 99% where i need to cheat it in a way to always be equal to 100%..
Here is the PHP
$charity = $_POST['charity'];
$sql = "SELECT amount FROM charities";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
$total += $row['amount'];
}
$sql_individual = "SELECT * FROM charities WHERE charity='$charity'";
$result_individual = mysqli_query($con, $sql_individual);
while($row = mysqli_fetch_array($result_individual)) {
$charity = $row['amount'];
}
echo round($charity / $total * 100,0) . "%";
I found a maths solution for this.. but.. my maths isn't all that great.. but.. okay in all honesty i do not understand this fully:
c = 100 - (a + b) - e,g 34 = 100 - (33 + 33)
any Help Greatly Appreciated..
There are no rounding issues, You just round to an integer numbers, that means that if You have 5 values like these:
12,25%
13,25%
20,25%
30,25%
34,00%
after using round($x, 0) on them they will be rounded to these values:
12
13
20
30
34
After summing these rounded values You get the value of 99.
It is best to round at least to two decimal places when working with percentages - and only for displaying purposes. You shouldn't round any values that will be used for further math operation...

How to efficiently filter datetime column for extracting data?

I am usng sqlite to log data every 5 minutes to a column that is time stamped with and integer in Unix time. The user interface uses php code to extract data in various user selectable time frames which is then plotted using javascript. Charts typically have 12 data/time points and I need to extract data for plotting over different periods of say 1Hr/12Hr/24Hr/12days/month/year. So only need to extract 12 data rows per search. So for a 24Hr plot I need to only extract data at houly intervals (when minutes = 0) similarly for 12day plots at daily intervals (when mins=0 && hours=0) etc.
My php code for 1Hr works fine since the data is logged every 5min giving me 12 rows of data between search start time and end time. What is an efficient way of extracting data for the longer periods when number of rows between start time and end time is greater than 12? I need to further filter the search to efficiently extract only the data I need?
any suggestions - most appreciated - frank
$db = new MyDB(); // open database
$t=time(); // get current time
$q1 = "SELECT TimeStamp,myData FROM mdata WHERE ";
$q2 = " AND TimeStamp <=".$t; // end time
$q3 = " AND TimeStamp >=".($t-3600); // start time 1 hour earlier
$qer = $q1.$q2.$q3; // my search query form above parts
$result = $db->query($qer);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
echo json_encode($json); // data is returned as json array
$db->close(); // close database connection
I think you should use WHERE date BETWEEN in your search query?
This kind of search could take up a lot of time once data builds up?
Since you already know the exact times you're interested in, you should probably just build an array of times and use SQL's IN operator:
$db = new MyDB(); // open database
$timeStep = 300; // Time step to use, 5 minutes here - this would be 3600 for hourly data
$t = time(); // get current time
$t -= $t % $timeStep; // round to the proper interval
$query = "SELECT TimeStamp,myData FROM mdata ";
$query .= "WHERE TimeStamp IN "
$query .= "(" . implode(",", range($t, $t + $timeStep * 12, $timeStep)) . ")";
$result = $db->query($query);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
You'll need to do some different math for monthly data - try constructing 12 times with PHP's mktime() function.
Here are the references for the PHP implode() and range() functions I used.

Categories