Replacing redundant dates in DB query with symbol (MySQL/PHP) - php

I have a database query that displays a list of historic events in chronological order, like this:
(URL = MySite/Calendar/January_1)<br>
On this day in history...<br>
1968 - A volcano erupted.<br>
1968 - A country was invaded.<br>
1968 - Someone had a hit song.<br>
1970 - A famous person was born.
I'd like to know if there's a way to display a year just once, so the display looks like this:
1968 - A volcano erupted.<br>
• A country was invaded.<br>
• Someone had a hit song.<br>
1970 - A famous person was born.
Let's start with a database table (calendar_px) that lists the dates of various historic political events. The table has five fields -
1) N (a simple numerical key)
2) URL (values - such as May_1 - match page URL's)
3) Year (e.g. 1970, but the field type is INT, not Year, which only goes back to 1901)
4) Brief (some brief content)
5) Date (field type will be either date or datetime; I'm not actually using this field at the moment)
Here's what my code looks like (where $MyURL equals the page URL; e.g. January_1):
$stm = $pdo->prepare("SELECT Cal2.N, Cal2.URL, Cal2.Date, Cal2.Year, Cal2.Brief
FROM calendar_px Cal2
WHERE Cal2.URL = :MyURL
ORDER BY Cal2.Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
while ($row = $stm->fetch())
{
$Year = $row['Year'];
$Brief[] = ''.$Year.' – '.$row['Brief'].'';
}
Then, I display a list of historic events like this...
echo join( $Brief, '<br>' );
I don't think it really changes anything, but I should mention that I have a similar set up on several websites; everything is the same except for the table names:
calendar_gw, calendar_gz, calendar_gs, calendar_px, calendar_sl
Accordingly, I've joined all five tables together with a UNION command. Here's a portion of the query:
$stm = $pdo->prepare("SELECT CGW.N, CGW.URL, CGW.Date, CGW.Year, CGW.Brief
FROM calendar_gw CGW
WHERE CGW.URL = :MyURL
UNION ALL
SELECT CGZ.N, CGZ.URL, CGZ.Date, CGZ.Year, CGZ.Brief
FROM calendar_gz CGZ
WHERE CGZ.URL = :MyURL
UNION ALL
SELECT CSL.N, CSL.URL, CSL.Date, CSL.Year, CSL.Brief
FROM calendar_sl CSL
WHERE CSL.URL = :MyURL
ORDER BY Year");
$stm->execute(array(
'MyURL'=>$MyURL
));
Anyway, my goal is the same; to replace redundant dates (years) with some sort of "dingbat" or symbol.

$prevYear = null;
while ($row = $stm->fetch())
{
$Year = $row['Year'];
if ($Year == $prevYear) {
$YearStr = '• ';
} else {
$YearStr = $Year . ' $#8211; ';
$prevYear = $Year;
}
$Brief[] = $YearStr.$row['Brief'];
}
P.S. You don't need to concatenate '' at each end of the string.

Looks like you need to group resultset before outputting:
$events = array();
while($row = $stm->fetch()){
$year = $row['Year']; // current year
if(!isset($events[$year]){ // if no such group
$events[$year] = array(); // create group
}
$events[$year][] = $row['Brief']; // add data to year group
}
// Output:
foreach($events as $year => $event){
echo $year, ':<br>'; // show year;
foreach($event as $data){
echo $data, '<br>'; // show row;
}
}
Also, you may change output to your model, easily:
foreach($events as $year => $event){
echo $year, ' • ', implode('<br>• ', $event);
}

Related

value ($age) returns unexpected result

Ideally what should happen is, based on the in-game date that the site is set to (currently its 3014-11-16) the site should calculate a characters current age and return that age. So if we set the Year to ignore year to 10 and a characters Date of Birth to 2, we would get an age of 8.
The current date is set to: 3014-11-16 (yyyy-mm-dd)
The date of birth for timber wolf is: 2998-01-12 (yyyy-mm-dd)
His age should display as 16, instead it displays as -55
If i set his DOB to: 3013-11-16, his age become -71
If i set his DOB to: 3012-11-16, his age come back -70
If i set his DOB to: 3005-11-16, his age comes back as -63 instead of 7
If i set his DOB to: 2998-11-16, his age comes back as -56 instead of 16
If i set his DOB to: 2945-11-16, his age come back as -3
If i set his DOB to: 2944-11-16, his age comes back as -1
If i set his DOB to: 2943-11-16, his age comes back as 0
If i set his DOB to: 2105-11-16, his age come back 837 instead of 909
I've tried to minimize the code by removing a lot of the key array and parts that are not related to the problem. If I set the $age at the very last line to $age=15, I get fifteen, so I know that I am trying to revise the value being returned to the $age variable, but I'm completely lost after many attempts.
I'm looking for a way to get the correct age of the character. Thats my goal, hopefully someone out there can see what i'm doing wrong.
Here is the relevant code:
require_once('../include/Application.php'); // The only class we need to include
$app = new Application(); // Create the initial application object
$app->connect(); // Connect to the mysql server
$sess = new Session(); // Start a new session
$current = new CurrentUser(FALSE);
if ($current->errors) {
$errors = $current->errors;
trigger_error(current($errors), E_USER_ERROR);
}
include ("../functions.php");
$id="";
$record=array();
approveVars(array("id"));
$PHP_SELF = $_SERVER["PHP_SELF"];
$errors = array();
// Get daytimes from db
$daytimes = new DaytimeList();
if ($daytimes->errors) {
$errors = $daytimes->errors;
trigger_error(current($errors), E_USER_ERROR);
}
// Get the current game from the db
require_once('../include/Game.php');
$cu_game = new Game();
$cu_game->selectCurrent();
if ($cu_game->errors) { // Query error
$errors = $cu_game->errors;
trigger_error(current($errors), E_USER_ERROR);
} elseif ($cu_game->id) { // We got the current game
list($gametime, $realtime, $daylength, $inittod) = array(htmlspecialchars($cu_game->gametime, ENT_QUOTES), htmlspecialchars($cu_game->realtime, ENT_QUOTES), $cu_game->daylength/604800, htmlspecialchars($daytimes->data[$cu_game->inittod], ENT_QUOTES));
}
/*
$gametimefile = "$basefile/gamedate/gamedate.txt";
$tempy = file($gametimefile);
$gametime = trim($tempy[0]);
$realtime = trim($tempy[1]);
*/
if ($id) {
// FORMULA FOR GAME TIME
// FROM_DAYS(TO_DAYS('$gametime') + FLOOR((TO_DAYS(NOW()) - TO_DAYS('$realtime')) /14))
if (!is_numeric($id)) {
$characterSQL = "SELECT *, DATE_FORMAT(lastmodified,'%b %e # %h:%i %p') AS modformat, TO_DAYS(NOW()) - TO_DAYS(lastmodified) as modage, IFNULL(FLOOR((TO_DAYS('$gametime') + FLOOR((TO_DAYS(NOW()) - TO_DAYS('$realtime')) / 14) - TO_DAYS(dateofbirth)) / 365.25) ,0) AS age, DATE_FORMAT(dateofbirth, '%b %e, %Y') AS dateofbirth, datecreated AS dateadded FROM cerebra where codename=\"". mysql_real_escape_string($id) . "\"";
} else {
$characterSQL = "SELECT *, DATE_FORMAT(lastmodified,'%b %e # %h:%i %p') AS modformat, TO_DAYS(NOW()) - TO_DAYS(lastmodified) as modage, IFNULL(FLOOR((TO_DAYS('$gametime') + FLOOR((TO_DAYS(NOW()) - TO_DAYS('$realtime')) / 14) - TO_DAYS(dateofbirth)) / 365.25) ,0) AS age, DATE_FORMAT(dateofbirth, '%b %e, %Y') AS dateofbirth, datecreated AS dateadded FROM cerebra where id=\"" . mysql_real_escape_string($id) . "\"";
} // end if'
$result=mysql_query($characterSQL, $db);
if (!mysql_num_rows($result)) { errorpage("There is no Cerebra record with that id number. Please check the link you used to access this page and try again, or check the <a href='/cerebra.php'>Cerebra main page</a> for the record you're looking for."); die; }
$record = mysql_fetch_assoc($result);
$id = $record["id"];
} else {
header("location: /cerebra.php");
die; } // end if ID
// "modelname","song","song_link"
//"Model", "Song", "Song Link",
$fields = array(
"Age"=>"age",
"Apparentage Age"=>"apparentage",
"Base Of Operations"=>"baseofoperations",
"Birthdate"=>"dateofbirth"
);
$patterns = array ("/\"/","/[\n\r\f]+/");
$replace = array (""","</p>\n<p>");
FOREACH ($fields as $label => $field) {
${$field} = preg_replace($patterns, $replace, trim($record[$field]));
${$field . "Name"} = $label;
} // end FOREACH
if ($age > "2000") { $age =""; }
//if i set $age = 15 here, then character age will appear as 15...

sum of 2D array in php

I have a situation where I need to generate total sales of each month.
I can show total sales of 12 month in a certain area but I need to show total sales of any month of a certain area. i.e: total sales of June at Head Office area.
my sample code is as follows:
while($area = mysql_fetch_array($exe_area))
{
for ($m=1; $m<=12; $m++) {
.........
echo $total_sold;
$sales_of_year+= $total_sold;
} // end of month listing....
echo $sales_of_year;
} // end of area listing...
U may try this !!!
$tmp = explode( '|', $str );
$data = array();
foreach ( $tmp as $k => $v )
{
$data[] = explode( ',', $v );
}
It looks like your data is being retrieved from the database, in which case you can extract the total sum with your query:
SELECT SUM(column_name) FROM table_name;
Or, to analyse a particular month, depending on your database schema, you can do:
SELECT SUM(column_name) FROM table_name WHERE month = 'June';

multiple dates datetime

I am trying to display a table with PHP MYSQL where the FIELD is the DATE and rows are TIME from a MySQL database with unknown/infinite records, one with different TIMES for the same DATE, by querying it for the DateTime.
My mysql date stores the dateTime in the same column, but I am splitting this and trying to display them seperately. BUT I cannot seem to display the date only once and the time multiple times, it is just both.
$sql_result = mysqli_query($connection, "SELECT DATE(date_time) AS date_part, TIME(date_time) AS time_part FROM $table WHERE date_time LIKE '$date_input%'");
if (mysqli_num_rows($sql_result) == 0)
{
echo "<p>No bookings exist.</p>";
}
else {
echo "<h3>Results for booked " . $table . " Appointments:</h3>";
echo "<h3>" . $formattedDate ."</h3>";
while ($row = mysqli_fetch_array($sql_result))
{
echo $row['date_part'];
$array_time = array($row['time_part']);
foreach ($array_time as $time_output)
{
echo $time_output;
}
}
}
My output is like this:
2013-12-0809:00:002013-12-0810:00:002013-12-0811:00:002013-12-0812:00:002013-12-0814:00:002013-12-0815:00:002013-12-0816:00:002013-12-0817:00:002013-12-0909:00:002013-12-0809:00:00
But I would like it like this:
2013-12-08 09:00:0010:00:0011:00:0012:00:0014:00:0015:00:0016:00:0017:00:0009:00:000
2013-12-09 9:00:00
Hrrmm. Theres a bit of logic problem here:
while ($row = mysqli_fetch_array($sql_result))
{
echo $row['date_part'];
$array_time = array($row['time_part']); // HERE
foreach ($array_time as $time_output)
{
echo $row['time_part'];
}
}
$array_time will always have only one value, since $row['time_part'] only refers to ONE row (each iteration of while ($row = mysqli_fetch_array($sql_result)) reassigns a single row to $row)
try doing this first pass to define a workable array
while ($row = mysqli_fetch_array($sql_result))
{
$array[$row['date_part']][$row['time_part']] = 1; // the value assigned doesn't matter, all we wish is a definite hierarchy
}
this will give you an array like:
['2013-12-08']['9:08'] = 1
['12:30'] = 1
[23:17] = 1
['2013-12-09']['10:00'] = 1
[14:20] = 1
THEN! you can foreach through your result
foreach ($array as $date_part => $array_time)
{
echo $date_part . ' ';
foreach ($array_time as $time_part => $i) // again our $i is not used
{
echo $time_part;
}
echo '<br>'; // here it breaks line after all times for the date has been echoed
}
You need to GROUP in your query:
SELECT DATE(date_time) AS date_part, TIME(date_time) AS time_part
FROM $table
WHERE date_time LIKE '$date_input%'
GROUP BY date_part
I think I understand what you're trying to say, however, MySQL won't create a multidimensional array. You should try something like this:
$dates = array();
while ($row = mysqli_fetch_array($sql_result)) {
$dates[$row['date_part']][] = $row['time_part']
}
Then you could have something like this:
foreach ($dates as $key => $value) {
echo $key.'<br />';
foreach ($value as $time) {
echo $time.' - ';
}
echo '<br />';
}
which should look something like:
2013-09-01
09:00 - 09:30 - 10:20 - 11:00
2013-09-02
10:12 - 11:00 - 12:24 //etc
Hope this helps!
Two comments. First, it seems like you need an order by time so as to order your records.
SELECT DATE(date_time) AS `date_part`, TIME(date_time) AS `time_part`
FROM $table
WHERE date_time LIKE '$date_input%'
ORDER BY date_time ASC
Second, if I read your question correctly, it seems like you want to output your data into two columns, one with date and the other with all times for that date. You might consider using GROUP_CONCAT() to do this in SQL, making your output easy.
SELECT DATE(date_time) AS `date_part`, GROUP_CONCAT(TIME(date_time)) AS `times`
FROM $table
WHERE date_time LIKE '$date_input%'
GROUP BY `date_part`
ORDER BY date_time ASC
This would give output like
date_part times
2013-12-08 11:22:33,11:33:44,12:44:55
2013-12-09 12:00:00
With this approach, there would be no need to build a multi-dimensional array in PHP, as the data would come out of the database just the way you need it. That also means that you don't need to load the entire result set into memory in order to work with it (as you would have to do if creating multi-dimensional array).

Making an array out of variables and update its contents based on one of the variables

I have a question that pertains to gathering events from tables in a calendar program where they are separated into "events" or "repeated events". I can get all individual events perfectly well now (thanks to Chris on this site), but if they are repeating events I have to calculate it from what is given in this particular db. If I change the types or the data in the db, it will probably trash the calendar so I have to use what I have.
The variables I have sorted out so far are:
$quid2 = The IDs for today's events that are classified as repeating events (needed earlier)
$quname = The repeated event names
$qucls = The date UNIX time for the last sent reminder of events dated today
$qutype = One of these words - daily, weekly, monthly or yearly
$qudesc = A description of the event
These variables all have the same number of items and are ordered correctly between each other. (I Hope)
Below is the logic I am trying to accomplish. It are most assuredly not proper syntax but I think it is understandable; I need to figure out what the syntax and form is. I am utterly and completely new at this... so please be gentle...
It needs to be put in an array (I think)
$arr1 = some type of array($quname, $qucls, $qutype, $qudesc)
update the array...
IF $qutype($row2) = "daily", then + 1440 to it's $qucls($row[1])
IF $qutype($row2) = "weekly", then + 10080 to it's $qucls($row[1])
IF $qutype($row2) = "monthly, then + 1 month to it's $qucls($row[1])
IF $qutype($row2) = "yearly", then + 1 year to it's $qucls($row[1])
Then final product...
while ($row = mysql_fetch_array($arr1, MYSQL_NUM)) {
$UxTime = $row[1];
date_default_timezone_set('America/Denver');
$Time = date("H:i", $UxTime);
$qufinal = sprintf("Event: %s \nTime: %s \nDesc: %s \n\n", $row[0], $Time, $row[3);
}
...
This is a big learning project for me. I don't know enough PHP and mysql to make this work but I know just enough to get me in trouble. Thanks!
EDIT: adding the queries from which I made these variables:
$today = date("Ymd");
mysql_select_db($dbname);
$query1 = "SELECT cal_id, cal_name, cal_date, cal_time, cal_type, cal_description FROM webcal_entry WHERE cal_type = "M" AND cal_date != " . $today;
$wequ1 = mysql_query($query1)
while ($row = mysql_fetch_array($wequ1, MYSQL_NUM)) {
$quid1 = $row[0], $quname = $row[1], $qutime = $row[2], $qudesc = $row[3];
}
$query2 = "SELECT cal_id, cal_type, cal_ByDay FROM webcal_entry_repeats WHERE cal_id = " . $quid1;
$wer1 = mysql_query($query2)
while ($row = mysql_fetch_array($wer1, MYSQL_NUM)) {
$quid2 = $row[0] $qutype = $row[1], $qubdy = $row[2];
}
$query3 = "SELECT cal_id, cal_last_sent FROM webcal_reminders WHERE cal_id = " . $quid2;
$wer2 = mysql_query($query3)
while ($row = mysql_fetch_array($wer2, MYSQL_NUM)) {
$qucls = $row[1];
}
The syntax for arrays is as follows:
$arrayName = array($quname, $qucls, $qutype, $qudesc);
Then you can access the values by their index on the array variable:
$arrayName[0] == $quname
$arrayName[1] == $qucls
...
You can also define it as associative array:
$arrayName = array(
"quname" => $quname,
"qucls" => $qucls,
"qutype" => $qutype,
"qudesc" => $qudesc
);
Using this syntax you can access the elements by their name:
$arrayName["quname"] == $quname
$arrayName["qucls"] == $qucls
...
More reading on this: Arrays
However, you don't really need an array for what you plan to do here. Arrays are very useful if you want to store data that is structurally equal. This applies e.g. to rows in a database: They always have the same number of entries, and the columns are of the same type.
If you have just one dataset at that point of code (one event in this case), then you need no array. Of course you have several events, but as they are processed in a loop (I assume) you handle only one event at a time, and then head to the next.
So, you want to modify a variable depending on the value $qutype. To do that, you can use a switch statement:
$dateObj = date_create("#$qucls");
switch($qutype) {
case "daily":
date_add($dateObj, date_interval_create_from_date_string("1 day"));
break;
case "weekly":
date_add($dateObj, date_interval_create_from_date_string("1 week"));
break;
case "monthly":
date_add($dateObj, date_interval_create_from_date_string("1 month"));
break;
case "yearly":
date_add($dateObj, date_interval_create_from_date_string("1 year"));
break;
}
$qucls = date_format($dateObj, "U");
I don't add the number of seconds, because that would work for days and weeks- but not for months and years, as they don't have a fixed number of seconds.
If you have questions about the functions I used above you can look up their documentation on php.net.
In the code you show you must not use mysql_fetch_array.
That function is only meant for result rows you got from a call to mysql_query, but not for normal arrays.
You don't need the while loop either. All you have to do is formatting $qucls to a readable format and produce the final string:
date_default_timezone_set('America/Denver');
$Time = date("H:i", $qucls);
$qufinal = sprintf("Event: %s \nTime: %s \nDesc: %s \n\n", $quname, $Time, $qudesc);
Edit:
Like discussed in the comments here is the revised and commented code you edited in:
$today = date("Ymd");
mysql_select_db($dbname);
// You need to use single quotes at the 'M'. Using double quotes will
// end the string and thus leading to incorrect syntax
$query1 = "SELECT cal_id, cal_name, cal_date, cal_time, cal_type, cal_description FROM webcal_entry WHERE cal_type = 'M' AND cal_date != " . $today;
$wequ1 = mysql_query($query1);
// This is a counter variable which is incremented in the loop
$i = 0;
// This is the outer while loop used to gather and store the events
while ($row = mysql_fetch_array($wequ1, MYSQL_NUM)) {
// Store the results in arrays
// Statements must be seperated by a ;
$quid1[$i] = $row[0];
$quname[$i] = $row[1];
$qutime[$i] = $row[2];
$qudesc[$i] = $row[3];
$query2 = "SELECT cal_id, cal_type, cal_ByDay FROM webcal_entry_repeats WHERE cal_id = " . $quid1[$i];
$wer1 = mysql_query($query2);
// Assuming that IDs are unique this query can only return one entry. Therefore no while is
// needed, but an if statement tests if the ID actually matched a result
if ($row = mysql_fetch_array($wer1, MYSQL_NUM)) {
//$quid2[$i] = $row[0]; <- the query above ensures that $quid1[$i] == $quid2[$i]. No need to store it again
$qutype[$i] = $row[1];
$qubdy[$i] = $row[2];
}
$query3 = "SELECT cal_id, cal_last_sent FROM webcal_reminders WHERE cal_id = " . $quid1[$i];
$wer2 = mysql_query($query3);
// Same as above; If the IDs are unique then you need no loop
if ($row = mysql_fetch_array($wer2, MYSQL_NUM)) {
// The $i++ used here is the short form. As this is the last time $i is
// used in the loop it needs to be increased before the next round. You can do
// this like this or in an extra statement. This way it's evaluated and then increased
$qucls[$i++] = $row[1];
}
// End outer while loop
}
// Now go through the results. $i holds the number of entries in the arrays + 1
// Secondary counter variable and for-loop
for ($j = 0; $j < $i; $j++) {
// Adding the dates to $qucls, formatting the string, ...
// Access them like above: $qucls[$j]
// Do not increase $j manually though - the for loop does that for you already
}
Please note that this code is untested. It's syntactically correct though.
On a side note: You are currently using three different database queries to gather the data.
You can easily merge them into a single query using SQL JOINs. If you want somebody to show you how to do that, you can show them in a seperate question and ask for them to be joined into one.

How to break up reports by month with php and mysql?

I'm trying to do something relatively simple here. Basically I have a table with a bunch of rows in it marked with a timestamp (format: 2009-05-30 00:14:57).
What I'm wanting to is do is a query which pulls out all of the rows, and splits them by the month so I'm left with a final result like:
February
rowID name order date
rowID name order date
rowID name order date
January
rowID name order date
rowID name order date
rowID name order date
etc.
I have a few vague ideas how to do this - they just seem long winded.
One of the ways would be to do a query for each month. I'd derive what the current month is in PHP then construct a for() which goes back a certain number of months.
like:
$currentmonth = 8;
$last6months = $currentmonth - 6;
for($i = $currentmonth; $i == $last6months; $i--) {
$sql = 'SELECT * FROM reports WHERE MONTH(reports.when) = $currentmonth ';
$res = mysql_query($sql);
// something would go here to convert the month numeral into a month name $currentmonthname
echo $currentmonthname;
while($row = mysql_fetch_array($res)) {
// print out the rows for this month here
}
}
Is there a better way to do this?
It's better to fetch all data once,ordered by month..
Then while fetching with php you can store your current month in a variable (for example $curMonth) and if there is a change in the month, you echo "New Month"...
Executing a query is slow, it's better to minimize your "conversations" with the db..
Don't forget that you have to deal with years aswell. If you have two records, one for January '09 and one for January '08, your results may be skewed.
Best to follow Svetlozar's advice and fetch all data at once. Once you have it in memory, use PHP to segment it into something usefull:
$monthData = array();
$queryResult = mysql_query("
SELECT
*,
DATE_FORMAT('%m-%Y', when) AS monthID
FROM
reports
WHERE
YEAR(when) = 2009 AND
MONTH(when) BETWEEN 5 and 11
");
while ($row = mysql_fetch_assoc($queryResult))
{
if (!isset($monthData[$row['monthID']]))
$monthData[$row['monthID']] = array();
$monthData[$row['monthID']][] = $row;
}
mysql_free_result($queryResult);
foreach($monthData as $monthID => $rows)
{
echo '<h2>Data for ', $monthID, '</h2>';
echo '<ul>';
foreach($rows as $row)
{
echo '<li>', $row['someColumn'], '</li>';
}
echo '</ul>';
}
You could change your SQL query to get your entire report. This is much more efficient than querying the database in a loop.
select
monthname(reports.when) as currentmonth,
other,
fields,
go,
here
from reports
order by
reports.when asc
You could then use this loop to created a nested report:
var $currentMonth = '';
while($row = mysql_fetch_array($res)) {
if($currentMonth !== $row['currentMonth']) {
$currentMonth = $row['currentMonth']);
echo('Month: ' . $currentMonth);
}
//Display report detail for month here
}
*Note: Untested, but you get the general gist of it I'm sure.
This is the SQL script:
SELECT*, DATE_FORMAT(fieldname,'%Y-%m') AS report FROM bukukecil_soval WHERE MONTH(fieldname) = 11 AND YEAR(fieldname)=2011
I hope you know where you should put this code :D

Categories