PHP fill array with sum of mysql column - php

I am kind of a novice in programming. I am trying to create an array from a MySQL table, which I will use later to create a graph in PHP/Javascript.
The entire idea is, that I want to make an array, filled with data representing every week of the year. So, an array with 52 entries (lets forget the 53'rd week which occurs sometimes).
My database:
I have 1 table in my database which I use for this:
+-------------------------+
I production I
+-------------------------+
I Shift I (number) I <-ranging from 1 to 3 (different shifts people make)
I Line I (number) I <-ranging from 1-8 (different 'conveyor belts')
I Products I (number) I <-ranging from 0- a lot! (To be entered in a form)
I Week I (number) I <-ranging from 1 to 52
+-------------------------+
Now, the idea is, that I want an array, filled with the SUM of all the products.
The SUM(Products) must exist of the following:
Sum of all products per shift + line.
Shift 1, Line 1, made 10,000 products
Shift 1, Line 2, made 15,000 products
Shift 1, Line 3, made 20,000 products (etc etc)
SUM(Products) will be all products from shift 1 to 3, and all lines 1 to 8.
So: 10,000 + 15,000 + 20,000 etc etc.
I want this total to be put inside an array, having 'week 1' as my array keys.
So for the first week you get:
$array (
"1" => // SUM(products) of week 1 (which was the 10,000 + 15,000 + 20,000 etc)
"2" => // SUM(products) of week 2
"3" => // SUM(products) of week 3
// etc.
Can I do this by adding 52 different MySQL-Queries, with the only difference WHERE week='x'?
So far I have only been experimenting with code found on the interwebz.
Any help would be greatly appreciated! :D
Greetings from Holland

Just take out the WHERE clause, and you'll get results for every week.
$result = mysql_query("SELECT week, SUM(products) AS total
FROM production GROUP BY week");
The results will be returned as successive rows from the result set, and you can put them into an array:
$sum_by_week = array();
while ($row = mysql_fetch_assoc($result)) {
$sum_by_week[$row["week"]] = $row["total"];
}
PS: You didn't ask for this, but you should be aware that the mysql_* functions are being deprecated. You should start using the mysqli functions or PDO for new PHP applications. Only if you're just maintaining an existing application is it worthwhile to continue using the old mysql_* functions.

Apologies in advance for using mySQL instead of another extension. ;-)
<?php // RAY_temp_rowan.php
error_reporting(E_ALL);
echo "<pre>";
// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??"; // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";
// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>NO DB CONNECTION: ";
echo "<br/> $errmsg <br/>";
}
// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>NO DB SELECTION: ";
echo "<br/> $errmsg <br/>";
die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES
// CREATING A TABLE
$sql = "CREATE TEMPORARY TABLE my_table (
_key INT NOT NULL AUTO_INCREMENT,
shift INT NOT NULL DEFAULT 0,
line INT NOT NULL DEFAULT 0,
products INT NOT NULL DEFAULT 0,
week INT NOT NULL DEFAULT 0,
PRIMARY KEY(_key) )";
$res = mysql_query($sql);
// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>QUERY FAIL: ";
echo "<br/>$sql <br/>";
die($errmsg);
}
// LOAD UP THE TABLE
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,2,4000, 1)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,4,4000, 1)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,2,4000, 2)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,4,5000, 2)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,2,4000, 3)') or die(mysql_error());
mysql_query('INSERT INTO my_table (shift, line, products, week) VALUES (1,4,6000, 3)') or die(mysql_error());
// MAKING A SELECT QUERY AND TESTING THE RESULTS
$sql = "SELECT week, SUM(products) as sump FROM my_table GROUP BY week ORDER BY week ASC";
$res = mysql_query($sql);
// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
$errmsg = mysql_errno() . ' ' . mysql_error();
echo "<br/>QUERY FAIL: ";
echo "<br/>$sql <br/>";
die($errmsg);
} // IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS
// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE SELECTED
while ($row = mysql_fetch_assoc($res))
{
$out[$row["week"]] = $row["sump"];
}
var_dump($out);

Related

show same id one time but in column count how many times php

I am displaying data from database, but I want to display one time same id but in other column how many times its stored in MySQL database.
Thanks!
if (!isset($_REQUEST['completed_consu_id'])) {
$query = "SELECT * FROM completed_consumers";
} else {
$query = "SELECT * FROM completed_consumers WHERE consu_id=consu_id";
}
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$numberofrow=mysql_num_rows($result);
while ($row = #mysql_fetch_array($result)) {
$consu_id = $row['consu_id'];
$consu_first_name = $row['consu_first_name'];
$consu_last_name = $row['consu_last_name'];
$consu_phone = $row['consu_phone'];
$consu_email = $row['consu_email'];
$consu_address = $row['consu_address'];
$consu_city = $row['consu_city'];
$consu_state = $row['consu_state'];
$consu_zip = $row['consu_zip'];
$consu_IP = $row['consu_IP'];
$status = $row['status'];
$query2 ="SELECT consu_id, COUNT(*) FROM completed_consumers WHERE consu_id=$consu_id GROUP BY consu_id";
$result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());
$numberofrow2=mysql_num_rows($result2);
$times= $numberofrow2;
echo $times;
This is code i have written, Its displaying all the consumers details and how many they have entered data or details, but I want to show one time consumer details/Name but how many time they submitted data in "times" column.
Like David consumer added 2 times, Monika added 1 time, Arshi added 3 times data/details, but when i retrieve data its showing 6 rows in table, i want to show in 3 row, 1 for David, 1 for Monika, 1 for Arshi but with how many times they added in "times" column when i retrieve it details.
Take a look at the GROUP BY clause.
SELECT id, COUNT(*) FROM completed_consumers WHERE consu_id=$consu_id GROUP BY consu_id

add rows with loop max value +1

I'm trying to add rows to the database based on the input value.
i.e. If input as "5", query will insert 5 rows to database. (this part is working fine)
Now, I need the bed_number to be +1 to the existing max(bed_number) but i can't seems to get it to work.
If existing max(bed_number) returns 5, than the query should add "6,7,8,9,10, etc" as the bed_number for the 5 entries.
If existing max(bed_number) returns null, than it should add "1,2,3,4,5, etc"
Right now, the result always return 1,2,3,4,5... regardless of the max count.
What i have here now is:
global $conn;
if ($values["number_of_bed"])
{
$add1 = $values["number_of_bed"]+1;
$existingBed = "select Max(bed_number) from bed where bed =" '".$i."'" +1;
for ($i=1;$i<$add1;$i++)
{
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$existingBed."')";
db_exec($strInsert,$conn);
}
header("Location: bed_list.php");
// Exit and Redirect to the list page after updating database
exit();
//echo "Number of customers: " . $data["c"];
global $conn;
if ($values["bed_number"])
{
$add1 = $values["bed_number"]+1;
//for ($i=1;$i<$values["bed_number"];$i++)
for ($i=1;$i<$add1;$i++)
{
$sql = "select max(bed_number) as c from bed where unit_id =" . $values["unit_id"];
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$data["c"]."'+1)";
// add more fields from the add page to be inserted into database
db_exec($strInsert,$conn);
}
header("Location: bed_list.php");
// Exit and Redirect to the list page after updating database
exit();
}

mySQL to PHP dynamic table

This question has been asked many times but I'm sorry I still can't make it work.
I have a simple mySQL DB like this table:
In this DB I have a column with people and 3 other columns that represent days - Day 1, Day 2 and Day 3.
The letter "M" means Morning and "A" Afternoon.
So I want to query this DB and ask: "Who was working Day 1 in the morning?" and it returns "John".
I know how to do this query, but I don't know how to format the return.
Let's say that 3 people worked Day 1 morning (because the actual DB is bigger then this one) I want the HTML to return a 3 row table stating their names, but if only 2 persons worked Day one in the morning, it would return only a 2 row table stating their names.
This is my PHP:
<?php
$con = mysql_connect(".",".",".");
$db_selected = mysql_select_db("xbizh_14391723_horario", $con);
$sql = "SELECT `AM` FROM HORARIO WHERE `1` ='N'";
$result = mysql_query($sql);
$num = mysql_numrows($result);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_array($result))
{
print_r($row);
}
mysql_free_result($result);
?>
It seems to me you are most of the way there already.
print("<table>");
while($row = mysql_fetch_array($result))
{
print("<tr><td>" . $row['name_field'] . "</td></tr>");
}
print("</table>");
You also need to make sure your query is returning the name field.
$sql = "SELECT * FROM HORARIO WHERE `1` ='N'";
or
$sql = "SELECT `name_field` FROM HORARIO WHERE `1` ='N'";

php random mysql data

I have a MySQL database with 6 columns in a table. There will eventually be about 100 rows, for now I have 3.
Column titles: FirstName, SecondName, Sentence1, Sentence2, Sentence3, Sentence4
All tables are set to VARCHAR
I want to use php on a web page to call random data from each row, eg mix and match row1 FirstName with row3 SecondName and row2 Sentence1 etc.
I read it is quicker to randomise using php but I really can't grasp how to do this despite searching.
I can connect to my MySQL database and get results returned using this code:
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['FirstName'] . "<br />";
}
// Close the database connection
mysql_close();
?>
but this just returns one column of data. I need the random code to be returned in the webpage using something like:
echo $firstname . $lastname . $sentence1 . $sentence2 . $sentence3 . $sentence4;
Note, this will be repeated for another 3 or 4 rows afterwards too
echo $firstname_2 . $lastname_2 . $sentence1_2 . $sentence2_2 . $sentence3_2 . $sentence4_2;
I'm not too hot on arrays but if someone can get me started it would be great, thanks.
All those telling you to use rand in the SQL query have not read the question. To those people: the asker wants a random combination of data from the rows, not a random row.
Something like this. It will take all the results from the database and echo a totally random combination. I couldn't avoid using arrays as they are super useful.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>
Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them
there are several methods to get random data from db in php
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
another method: -
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
one more method:-
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
SELECT * FROM `Users` ORDER BY RAND() LIMIT 0,1;
Use ORDER BY RAND() for random records selection.
Split it into two tables,
one for the user
Users:
id | firstname | lastname
Sentences:
id | userId | sentence
Join both at the "id / userId" and do a ORDER BY RAND() probably followed by a LIMIT 20
Trying to implement this but taking an entry from every column (14 at present) instead of a small random number. Would love to have Matthew McGovern's opinion since his code suited me except that it only called a few entries...
Here: Random Sentence Using PHP & MySQL

Rolling Average Efficiency, php mysql

This script uses php and mysql to compute a one minute rolling average to reduce the impact of outliers on the my data (one minute = 6 10-second rows). It computes everything correctly, but is not efficient enough to do more than 150 rows at a time. I'd like to do as many rows as I can at a time, possibly between 5-10,000 as my table is over 150,000 and I input approximately 8,000 rows per day.
Does anyone have any suggestions as to how I can make this script run more efficiently?
Thanks!
<?php
//connect to database
mysql_connect("localhost","user","password");//database connection
mysql_select_db("database");
$result = mysql_query("SELECT Timestamp FROM table");
if (!$result) {
die('Could not query:' . mysql_error());
}
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
//select column to be averaged
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
if (!$resultB) {
die('Could not query:' . mysql_error());
}
//set start equal to the first row you want to calculate the averages from, likely the first null row
$start = 5;
//calculate 1 minute average, the average is correct
for($i = $start; $i<$num_rows; $i++){
$output = mysql_result($result,$i);
$test = mysql_result($resultB,$i)+mysql_result($resultB,$i-1)+mysql_result($resultB,$i-2)+mysql_result($resultB,$i-3)+mysql_result($resultB,$i-4)+mysql_result($resultB,$i-5);
$test2 = $test/6;
$round = round($test2,4);
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
//gets timestamp at row $i, and inserts new average value into that row in RPMAve column
$time = mysql_result($result,$i);
mysql_query("UPDATE table SET PortMinuteAveRPM = $round WHERE Timestamp = '$time'");
}
For starters, the initial "count" block here can be cleaned up by adding the COUNT() aggregate:
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
Change to:
$resultA = mysql_query("SELECT COUNT(*) FROM table");
$row = mysql_fetch_array($result);
$num_rows = $row[0];
echo "There are $num_rows rows.</br>";
That should speed things up considerably on its own. Without it, you're selecting all of the data from the table - a query that will only grow slower the more you put into the table.
For the averages you're computing, is there any logic required that can't be accomplished directly in a MySQL query? Something such as:
UPDATE table SET PortMinuteAveRPM=(SELECT AVG(PortRPMSignal) FROM table WHERE Timestamp BETWEEN '$startTime' AND '$endTime') WHERE TimeStamp='$endTime'
This may save you from looping through results, if it's plausible.
It sounds like you're trying to calculate an autoregressive moving average (ARMA) but there's numerous issues with your interpretation of your data and how you are capturing it.
If you've got a complete set of data (though your question implies that you don't), then work out what time interval contains the required amount of records and get it direct from the database, e.g.
SELECT a.timestamp as base, AVG(b.PortRPMSignal)
FROM table a, table b
WHERE b.timestamp BETWEEN a.timestamp AND a.timestamp+INTERVAL 6 HOUR
GROUP BY a.timestamp
If you want to thin out the datapoints, then try something like....
SELECT a.timestamp as base, AVG(b.PortRPMSignal)
FROM table a, table b
WHERE b.timestamp BETWEEN a.timestamp AND a.timestamp+INTERVAL 6 HOUR
AND DATE_FORMAT(a.timestamp, '%i%s')='0000'
GROUP BY a.timestamp
Although a better solution if you've not got a complete dataset but there's only a small amount of jitter would be to use the modulus of an auto-increment id to pick out fewer rows from 'a'
It's only a start, but you can bin this bit
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
Because the following line
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
...will give you a result set that you can use mysql_num_rows on.
Using the * in a query increases the load on the database.
In your for loop you then have this
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
which means this query runs every time you loop and you're not even using the results.
I don't know if mysqli will give you better performance, but you should use it.

Categories