Get the number of rows inserted in the database per hour - php

I know there are similar questions already, but I can't find a clear and simple answer.
I have this query :
"SELECT dbo.tbTransaction.dateHeure, dbo.tbTransaction.Etat, dbo.tbPoste.nomPoste
FROM dbo.tbTransaction
INNER JOIN dbo.tbPoste ON dbo.tbTransaction.ID_poste = dbo.tbPoste.ID_POSTE
WHERE dbo.tbPoste.id_site LIKE 47
AND dbo.tbPoste.nomPoste LIKE '0909_CLIENT'
AND dateHeure >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)
ORDER BY dateHeure DESC";
It enables me to fetch all the database insertions of the day(>= DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)) on a particular post (0909_CLIENT), sorted by the most recent time of insertion(ORDER BY dateHeure DESC).
I would like to be able to retrieve the number of inserts per hour, the goal is to be able to generate live graphics hour by hour.
I manage to get the total number of insertions during the day with :
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_num_rows( $result ). PHP_EOL;
echo '<br>';
if ($row_count === false)
echo "Error in retrieveing row count;
else {
echo $row_count;
}
I can see the lines entered in the database at a particular time with :
$five = "05:";
$six = "06:";
$seven = "07:";
if ($result === false) {
die(print_r(sqlsrv_errors(), true));
} else {
while ($row = sqlsrv_fetch_array($result)) {
$heureformate = $row["dateHeure"]->format('H:i');
if (strpos($heureformate, $five) !== false) {
echo $heureformate;
echo '<br>';
//count(array($heureformate));
} elseif (strpos($heureformate, $six) !== false) {
echo $heureformate;
echo '<br>';
} elseif (strpos($heureformate, $seven) !== false) {
echo $heureformate;
echo '<br>';
}
}
}
But as I told you, I don't manage to get the number of lines entered per hour and it's this number that interests me to create graphics.
If you have any ideas on how to get this number in SQL or PHP, please help me.

Do you want aggregation?
select datepart(hour, t.dateheure), count(*) as cnt
from dbo.tbtransaction t
inner join dbo.tbposte p on t.id_poste = p.id_poste
where p.id_site = 47 and p.nomposte = '0909_client' and t.dateheure >= cast(gedate() as date)
group by datepart(hour, dateheure)
This filters the dataset for rows whose dateheure belongs to the current day, and counts how many records there is in each hour.
Note that I simplified the date filtering logic, and turned the like conditions to equalities (since no wildcards are involved, both are equivalent).

Related

Creating a loop that checks several tables and counts the results depending on value

I'm not sure what to do when my if statement is true and how to count each hit.
My code first checks a table to get all the companies that are active.
I then want to go to each table for that company that is active, get the last entry, and count how many values for Status are either not equal to 3(!=3) or equals 2(==2).
I have no problems with this code giving me values from the row for each company but I'm not sure how to count this.
// Get a list of active companies
$sql_companyinfo="SELECT Name FROM Company_Info Where Active=True ORDER BY Name";
$result_companyinfo = mysqli_query($conn, $sql_companyinfo);
// Create variables and Loop for each active Company
while($prop_info = mysqli_fetch_assoc($result_companyinfo)) {
$prop_name = $prop_info["Name"];
$company_table = ("Company_" . "$prop_name");
// Query Table and get the last record added
$result_company = mysqli_query($conn,"SELECT * FROM $company_table WHERE ID=(SELECT MAX(ID) FROM $company_table)");
$row1 = mysqli_fetch_array($result_company);
//Status from Last Row Inserted
$Row_Status = $row1['Status'];
// This is where I get lost. For each company I need to know how many companies where $Row_Status != 3 or == 2
if ($Row_Status != '3') {
// Start with 0 and add 1 for each match
for($n3 = 0; $array[$n3]; $n3++) {
$n3_result = $n3;
}
} elseif ($Row_Status == '2') {
// Start with 0 and add 1 for each match
for($e2 = 0; $array[$e2]; $e2++) {
$e2_result = $e2;
}
{
echo "ERROR: Could not execute";
}
}
}
echo $n3_result;
echo $e2_result;
How to creating a loop that checks several tables and counts the results depending on value?
See you can do like this na:-
$Row_Status = '2';
if ($Row_Status != '3') {
echo 'ok1';
} else {
if ($Row_Status == '2') {
echo 'ok2';
} else {
echo 'ok3';
}
}

php mysql print list with db data

I'm trying to improve a php script that prints a list with db values and I need to make some complex (for me) operations to achieve what I want:
A list that prints the months and if they are paid or not, a bonus value with an extra bonus value for the first 3 ids and if the user already received it.
if ($stmt = $mysqli->prepare(" SELECT members.*, account_type.*, friends.*, friendsCount.friendID,
COUNT(friendsCount.friendID) AS num_f
FROM members
INNER JOIN account_type ON account_type.id = ?
INNER JOIN friends ON friends.friendID = ?
INNER JOIN friends AS friendsCount ON friendsCount.userID = ?
WHERE members.id = ?")) {
$stmt->bind_param('iiii', $_SESSION['acc_type'], $_GET['id'], $_SESSION['user_id'], $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
$monthNames = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
$paid = array(); //Placeholder for paid months.
for ($i = 1; $i < 13; $i++) {
$month = 'month' . $i;
$bonus_month = 'bonus_month' . $i;
// check if the user received the monthly bonus
if ($row[$bonus_month] == 0) {
// check if the friend's member account is active
if ($row['status'] == 1) {
// check if the friend paid the month
if ($row[$month] == 1) {
$paid[] = 'Pagado';
// check the user account type
if ($row['type'] == 'Base') {
// TODO: check if the friend is one of the three first (special promotion)
// (user gets double bonus for the first three invited friends)
if ($row['extra'] == 1) {
$extra = $row['bonus'] + 5;
$bonus[] = $extra . '€';
}
else {
$bonus[] = $row['bonus'] . '€';
}
}
else {
$bonus[] = $row['bonus'] . '€';
}
$cashed[] = 'No';
$non_cashed[] = $bonus[];
}
else {
$paid[] = 'No Pagado';
$bonus[] = 'n/a';
$cashed[] = 'n/a';
}
}
else {
$paid[] = 'n/a';
$bonus[] = 'n/a';
$cashed[] = 'n/a';
}
}
else {
$paid[] = 'Pagado';
$bonus[] = $row[$bonus_month] . '€';
// TODO: find a way to check if user already received the bonus
// 12 new columns? (bonus_received_month1-12)
if (1 == 0) {
$cashed[] = 'Si';
$total_cashed[] = $row[$bonus_month];
}
else {
$cashed[] = 'No';
$non_cashed[] = $row[$bonus_month];
}
}
}
//Now make the HTML list
foreach ($monthNames as $key => $month) {
echo '
<div class="list">
<ul>
<li><a class="month">' . $month . '</a></li>
<li><a class="status">' . $paid[$key] .'</a></li>
<li><a class="bonus">' . $bonus[$key] . '</a></li>
<li><a class="cashed">' . $cashed[$key] . '</a></li>
</ul>
</div>';
}
} else echo $mysqli->error;
Actually it's working quite well but somethings are not implemented yet:
1º The extra bonus value for the first 3 ids (not including the status 0 accounts).
2º A way to check if the user already received the bonus so can be displayed the balance and the total received:
First of, I'd like to improve the method that adds the extra bonus:
// this column contains 1 for the first 3 friendIDs
if ($row['extra'] == 1) {
$extra = $row['bonus'] + 5;
$bonus[] = $extra . '€';
} else $bonus[] = $row['bonus'] . '€';
To achieve this: I have to check for the first 3 friendIDs (where userID = $_SESSION[user_id]) and compare if one of those match the current $_GET['id'].
// the number of friends
$count = $row['num_f'];
// the current friendID
$f_id = $_GET['id'];
$match = 'the first 3 ids (with acc status 1)';
if ($count > 2 && $f_id == $match) {
$extra = $row['bonus'] + 5;
$bonus[] = $extra . '€';
} else $bonus[] = $row['bonus'] . '€';
And statistics info:
// not received
echo '<p>Total acumulado: ' . array_sum($non_cashed[]) . '€</p>';
// total received
echo '<p>Total recibido: ' . array_sum($total_cashed[]) . '€</p>';
The big problem that I'm facing here is: If one of the three first accounts is inactive (status 0) how to "take" the next one that is active...
If account 1 is inactive but 2 and 3 are not, the account number 4 should be eligible for the extra bonus. The numbers are just the order that come from "select friendID from friends where userID = ?"
I presume that I can use array_key_exists to check if the $f_id exist inside the array that contains the first 3 ids...
How can I make that? Sorry if I made some mistakes, I'm working for several hours.
The tables are:
1º members: get the friend info -> "id", "status" (0 or 1; inactive/active), "name" and "month1-12" (12 columns: 0 or 1; not paid / paid month)
2º account_type: get the user acc type and the bonus value -> "id" (members.acc_type), "type" (the type name) and "bonus" (5, 10, 15 etc...)
3º friends: get the user info related to his friend -> "friendID" (members.id, the invited user), "userID" (members.id, the user that invited a friend), "extra" (1 for the first 3 invited users and 0 for the rest; 1 is double bonus, 0 is normal bonus. This column is going to be deleted), "bonus_month1-12" (12 columns; 0 is for the current month or a future month, 1+ is the bonus the user gained this month)
And to check if the user already received the bonus, I'm thinking to add 12 more columns to know it. It'll be 0 for non-received and 1 for received, unless a better method is suggested :)

How to sum up values in a php column

Im trying to sum up all the values in this data base but for some reason i cant do i, I looked all over stack overflow and tried multiple methods but none seem to work. My current code is
<?php
error_reporting(0);
//INCLUDES//
include 'config.php';
//INCLUDES//
//DATA FETCH//
$rank=$_POST['R'];
$drank=$_POST['DR'];
//DATA FETCH//
//MYSQL STUFF//
$con=mysqli_connect($ip,$login,$password,$dbname);
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i'");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
echo $row[0];
}
?>
It connects to the database no problem. When I use echo $row[0]; it prints all the values of the column in order. Ive tried putting it into an array and printing it but it seems that doesnt work either. The only way it seems to work is when I add ALL the values in the column by removing WHERE rank='$i' in the SQL code which I dont want to do. Please help !
Try the following query :
$rankarr = array();
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$rankarr[] = $i;
}
$rankarr = implode(',', $rankarr);
$s=mysqli_query($con, "SELECT sum(rankprice) As myrank FROM cost WHERE rank in ($rankarr)");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
You now want to get the sum value of rankprice in one same rank. So the result of sum() will differ from the rank in one sql. You should tell mysql by adding group by clause, which group the table by rank and get the sum() of each group.
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i' GROUP BY rank ");

PHP if and while Statements not working properly

I have php code with two queries. One is in an Oracle database, with the result being about 100 rows of data (within the data there are SKU numbers). The other is in a mysql database with about 30 rows of data (with the data there are also SKU numbers).
I need to compare each SKU in the first query to the second query, line by line. If the SKU in the first query also appears in the second query, then I need it to echo the SKU.
All SKUs in the second query are in the first query, so I would expect the result to echo all 30 SKUs, but it does not. Depending on how I change the syntax, it echos 17 rows, 100 rows, or no rows at all.
It's worth noting that both queries work fine. The Oracle query is insanely long and has a lot of sub-queries in it, so I will not include that full query below. The Oracle query returns the results perfectly in SQL Developer, and the MySQL query returns the results perfectly in HeidiSQL. Both queries have been tested and echoed as tables in other php files to make sure that they were working fine.
Below is what the php file that I am trying to fix looks like so far;
<?php
$conn = oci_connect($user, $pswd, $hst);
$sql = oci_parse($conn,"[Really long Oracle Query]");
while ($row = oci_fetch_assoc($sql))
{
$sku = $row['SKU'];
$con = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
$sqls = "SELECT * FROM [table_name] WHERE [this_date_column] BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$result = mysql_query($sqls);
$mailer = NULL;
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer == 'false';
}
}
if ($mailer == 'false')
{
echo $m_sku;
echo "<br>";
}
}
?>
Again; there are only 30 SKUs in the MySQL query, but over 100 SKUs in the Oracle query. All SKUs in the MySQL query are definitely in the Oracle query.
Anyone see what I am doing wrong?
Thanks in advance,
-Anthony
You have basic sintacsis errors:
= is used to assign values
== compares 2 variables (not counsidering there type *)
=== compares 2 variables including there types.
your code should look something like this:
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer = false; // == is for comparison, = is for assign
}
}
if ($mailer === false)
{
echo $m_sku;
echo "<br>";
}
if($member == 'false'){...}
when 'false' is compared with == to a falsefull value (0, null, false, array(), '') .. it will NOT be mach it as it is parsed as a "not empty string" so it is not falsefull .
Here is your code with the MySQL connect moved outside the loop and the == assignment fixed.
<?php
//Connect to databases
$oracle = oci_connect($user, $pswd, $hst);
$mysql = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
//Get rows from Oracle
$oracle_result = oci_parse($oracle, "[Really long Oracle Query]");
$oracle_rows = array();
while ($row = oci_fetch_assoc($oracle_result)) $oracle_rows[] = $row;
//Get rows from MySQL
$mysql_sql = "SELECT * FROM [database_name] WHERE this_date_column BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$mysql_result = mysql_query($mysql_sql);
$mysql_rows = array();
while ($row = mysql_fetch_assoc($mysql_result)) $mysql_rows[] = $row;
foreach ($oracle_rows as $oracle_row) {
$oracle_sku = $oracle_row['SKU'];
foreach ($mysql_rows as $mysql_row) {
$mysql_sku = $mysql_row['sku'];
$mailer = null;
if ($mysql_sku == $oracle_sku) {
$mailer = false;
echo $mysql_sku . "<br>";
}
}
}

php sql find and insert in empty slot

I have a game script thing set up, and when it creates a new character I want it to find an empty address for that players house.
The two relevant table fields it inserts are 'city' and 'number'. The 'city' is a random number out of 10, and the 'number' can be 1-250.
What it needs to do though is make sure there's not already an entry with the 2 random numbers it finds in the 'HOUSES' table, and if there is, then change the numbers. Repeat until it finds an 'address' not in use, then insert it.
I have a method set up to do this, but I know it's shoddy- there's probably some more logical and easier way. Any ideas?
UPDATE
Here's my current code:
$found = 0;
while ($found == 0) {
$num = (rand()%250)+1; $city = (rand()%10)+1;
$sql_result2 = mysql_query("SELECT * FROM houses WHERE city='$city' AND number='$num'", $db);
if (mysql_num_rows($sql_result2) == 0) { $found = 1; }
}
You can either do this in PHP as you do or by using a MySQL trigger.
If you stick to the PHP way, then instead of generating a number every time, do something like this
$found = 0;
$cityarr = array();
$numberarr = array();
//create the cityarr
for($i=1; $i<=10;$i++)
$cityarr[] = i;
//create the numberarr
for($i=1; $i<=250;$i++)
$numberarr[] = i;
//shuffle the arrays
shuffle($cityarr);
shuffle($numberarr);
//iterate until you find n unused one
foreach($cityarr as $city) {
foreach($numberarr as $num) {
$sql_result2 = mysql_query("SELECT * FROM houses
WHERE city='$city' AND number='$num'", $db);
if (mysql_num_rows($sql_result2) == 0) {
$found = 1;
break;
}
}
if($found) break;
}
this way you don't check the same value more than once, and you still check randomly.
But you should really consider fetching all your records before the loops, so you only have one query. That would also increase the performance a lot.
like
$taken = array();
for($i=1; $i<=10;$i++)
$taken[i] = array();
$records = mysql_query("SELECT * FROM houses", $db);
while($rec = mysql_fetch_assoc($records)) {
$taken[$rec['city']][] = $rec['number'];
}
for($i=1; $i<=10;$i++)
$cityarr[] = i;
for($i=1; $i<=250;$i++)
$numberarr[] = i;
foreach($cityarr as $city) {
foreach($numberarr as $num) {
if(in_array($num, $taken[]) {
$cityNotTaken = $city;
$numberNotTaken = $number;
$found = 1;
break;
}
}
if($found) break;
}
echo 'City ' . $cityNotTaken . ' number ' . $numberNotTaken . ' is not taken!';
I would go with this method :-)
Doing it the way you say can cause problems when there is only a couple (or even 1 left). It could take ages for the script to find an empty house.
What I recommend doing is insert all 2500 records in the database (combo 1-10 with 1-250) and mark with it if it's empty or not (or create a combo table with user <> house) and match it on that.
With MySQL you can select a random entry from the database witch is empty within no-time!
Because it's only 2500 records, you can do ORDER BY RAND() LIMIT 1 to get a random row. I don't recommend this when you have much more records.

Categories