How to get exact number of columns, loop statement [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am making a loop that displays a table with 12 columns. It starts with the number 1912 and ends with 2013. The problem is, when it loops to 1920, it has no remainder and starts a new row. I need to get the code to make a new row after the 12th column.
This is the result I'm getting:
And here is what I have so far:
<?php
$columns = 12;
$Year = 1912;
echo "<table width="755" border="1">";
echo "<tr>";
while ($Year <= 2013) {
if (!($Year % $columns)) {
echo "</tr><tr>";
}
echo "<td>$Year</td>";
++$Year;
}
echo "</tr>";
echo "</table>";
?>

<?php
$columns = 12;
$Year = 1912;
$i=1;
echo "<table width=\"755\" border=\"1\">";
echo "<tr>";
while ($Year <= 2013)
{
if ($i==13)
{
echo "</tr><tr>";
$i=1;
}
echo "<td>$Year</td>";
$Year++;
$i++;
}
echo "</tr>";
echo "</table>";
?>

SOLUTION 1
You need to append and prepend columns for the years where this matches, like so:
And here's the code for doing so:
<?php
$columns = 12;
$startingYear = 1912;
$endingYear = 2013;
$realStartingYear = $startingYear;
$realEndingYear = $endingYear;
//Find the real starting year by going back a year until we hit the right one
while ($realStartingYear % $columns) {
$realStartingYear--;
}
//Find the real ending year by going forward a year until we hit the right one
while ($realEndingYear % $columns) {
$realEndingYear++;
}
echo '<table width="755" border="1">';
echo "<tr>";
for ($year = $realStartingYear; $year < $realEndingYear; $year++) {
if (!($year % $columns)) {
echo "</tr><tr>";
}
echo "<td>" . ($year >= $startingYear && $year <= $endingYear ? $year : "") . "</td>";
}
echo "</tr>";
echo "</table>";
?>
If you want to show the other columns as well, just change
echo "<td>" . ($year >= $startingYear && $year <= $endingYear ? $year : "") . "</td>";
to
echo "<td>" . $year . "</td>";
SOLUTION 2
You want to start the table with 1912, like so:
The code will be a lot simpler:
<?php
$columns = 12;
$startingYear = 1912;
$endingYear = 2013;
echo '<table width="755" border="1">';
for ($i = $startingYear; $i <= $endingYear; $i += $columns) {
echo "<tr>";
for ($j = 0; $j < $columns; $j++) {
echo "<td>" . ($i + $j) . "</td>";
}
echo "</tr>";
}
echo "</tr>";
echo "</table>";
?>

You want to wrap every 12 columns, just keep track of the current column and use that to determine when you should end the row (e.g. every 12th column) --
$col = 1;
while ($Year <= 2013 && $col++) {
if (!($col % $columns)) {
//...
Using $Year to determine when to wrap just complicates things.

Related

Highlight td elements with events

I am generating a calendar via PHP date() function, I also have an events table that has a name and date_start, what I want to do is to highlight the td elements that have events on them and leave the ones without with the basic formatting.
Basically, this is the script that loops the day:
<?php
echo "<tr>";
for ($i = 1; $i < $numDays+1; $i++, $counter++) {
$timeStamp = strtotime ("$year-$month-$i");
if($i == 1){
$firstDay = date ("w", $timeStamp);
for ($j = 0; $j < $firstDay; $j++, $counter++){
//blank space
echo "<td> </td>";
}
}
if($counter % 7 == 0 ){
echo "<tr></tr>";
}
$todayDate = date("Y-m-d");
if (date("Y-m-d", $timeStamp) == $todayDate) {
?>
<td class="today-date"><?php echo $i; ?></td>
<?php
} else {
?>
<td><?php echo $i; ?></td>
<?php
}
}
echo "</tr>";
?>
.today-date is a class to highlight the current day. This is my table columns:
id | name | description | date_start | date_end | time | pastor_id | pastor | category | venue
I would probably put my events into an array with a key for the start date, so you end up with something like:
$events = [
'2017-08-22' => [
'name' => 'Event Title',
],
'2017-08-28' => [
'name' => 'Event Title',
'name' => 'Event Title',
],
];
There are multiple ways of doing this from a DB. Something like this:
$events = [];
while($row = mysql_fetch_assoc($eventQuery))
{
$events[$row['start_date']][] = $row['name'];
}
Then in your loop, you can check the date for an event and put it in:
<td class="<?php echo (array_key_exists(date("Y-m-d", $timeStamp), $events)) ? 'has-event-class' : ''; ?>">
Making database queries for every day in the calendar will be very inefficient compared to pulling all, or even the months'.
I would also be inclined to move this into a function so it's not as long in your loop:
function highlightEventTD($timeStamp, $events)
{
$date = date("Y-m-d", $timeStamp);
return (array_key_exists($date, $events)) ? 'has-event-class' : '';
}
Then in your forloop:
<td class="<?php echo highlightEventTD($timeStamp, $events); ?>">
It also means that if you need to show the name of the event, you can use the same array and a function:
function getEvents($timestamp, $events)
{
$date = date("Y-m-d", $timeStamp);
return (array_key_exists($date, $events)) ? $events[$date] : null;
}
Ok, first of all, PHP7 doesn't like anymore open and close php tag many times... I changed syntax with echo.
So try this :
// here make a SQL query (only one query is enough)
// on your database, for example :
$dates = array();
$q = "SELECT * FROM `events`";
if($res = $pdo->query($q) {
if($res = $res->fetchAll(PDO::FETCH_OBJ)) {
if(sizeof($res) > 0) {
foreach($res as $k => $d) {
$events[$d['date_start']] = $d;
}
}
}
}
echo "<tr>";
for ($i = 1; $i < $numDays + 1; $i++, $counter++) {
$timeStamp = strtotime ("$year-$month-$i");
if($i == 1){
$firstDay = date ("w", $timeStamp);
for ($j = 0; $j < $firstDay; $j++, $counter++) {
echo "<td> </td>"; //blank space
}
}
if($counter % 7 == 0 ) {
echo "<tr></tr>";
}
if (date("Y-m-d", $timeStamp) == date("Y-m-d")) {
$class = "today-date ";
}
if (array_key_exists(date("Y-m-d"), $events)) {
$class .= "event-date ";
}
// 1. solution based on your code
echo "<td class=\"$class\">$i</td>";
// 2. alternative with events in each day :
echo "<td class=\"$class\">";
if(sizeof($eventsOfTheDay = $events[$d['date_start']]) > 0 {
foreach($eventsOfTheDay as $k => $event) {
echo '', $event['name'], '<br>';
}
}
echo "</td>";
}
echo "</tr>";

Fill a table vertically in php

I'd like to fill a table vertically. For example one name on one row, the age on the second row alternately, and limit the table to 4 columns:
Is this possible with this kind of code?
Here is my Code:
<?php
$age = array("26","16","17","19","24","30");
$name = array("adam","andrew","tim","mike","don","eddy");
echo "<table border=1>";
for($i=0;$i<count($age);$i++)
{
if ($i > 0 && $i % 4 == 0)
{
echo "</tr><tr>";
}
echo "<td>";
echo $name[$i];
echo "</td>";
echo "<td>";
echo $age[$i];
echo "</td>";
}
echo "</tr>";
?>
Please try this. It is not the most elegant way but will give you an idea and maybe improve your answer. I will suggest you maybe use multi-dimensional array to store age and name together.
$age = array("26","16","17","19","24","30");
$name = array("adam","andrew","tim","mike","don","eddy");
$ageChunks = array_chunk($age, 4); //divide age array into chunks of 4
$nameChunks = array_chunk($name, 4); //divide name array into chunks of 4
//print table data
function printData($td)
{
echo "<td> ".$td." <td>";
}
//print table row. Assumption here is $nameChunks and $ageChunks are same length.
function printRow($nameChunks, $ageChunks)
{
foreach ($nameChunks as $key=>$val) {
echo "<tr>";
array_map("printData", $nameChunks[$key]);
echo "</tr><tr>";
array_map("printData", $ageChunks[$key]);
echo "</tr>";
}
}
//print table
function printTable($nameChunks, $ageChunks)
{
echo "<table>";
printRow($nameChunks, $ageChunks);
echo "</table>";
}
printTable($nameChunks, $ageChunks);
you need to change condition
if ($i > 0 && $i % 4 == 0) to if ($i > 0 && $i % 2 == 0) because you print 2 columns per iteration

Echo out SQL result to create a timetable

I am having problems printing out a timetable using the results from a SQL statement and some HTML layout with PHP.
I have the times of the classes along the top of the page.
I am trying to put the days of the week along the side of the page and then check if the result of the SQL statement (containing a module) should be printed in the specific day and time.
//Print out the top of the array to display the times
echo "<div><table class='table table-bordered'><thead><tr><th></th><th>9-10</th><th>10-11</th><th>11-12</th><th>12-13</th><th>13-14</th><th>14-15</th><th>15-16</th><th>16-17</th></tr></thead><tbody>'";
//Now loop through the result of the SQL statement that contains the modules associated with the selected course
while($row = mysqli_fetch_array($result1)) {
for($d = 1; $d < 6; $d++){
$printday = $days[$d];
echo "$printday";
for($t = 9; $t < 17; $t++) {
if($row['Day'] == $d && $row['Time'] == $t){ //fix this area so that it moves along
echo "<td>" . $row['ModuleName'] . "<br/>\n " .$row['Location'] . "</td>";
} //if
else {
echo "<td></td>";
} //else
} //for 2
echo "</tr>";
} //for 1
} //while
The problem is that I am printing out Monday-Friday 3 times as there are 3 $row results. Any idea how I could get this to work.
Your looping through your data in the wrong spot, you first need to put that in an array so you can loop through it for each day/time.
//Print out the top of the array to display the times
echo "<div><table class='table table-bordered'><thead><tr><th>Day</th><th>9-10</th><th>10-11</th><th>11-12</th><th>12-13</th><th>13-14</th><th>14-15</th><th>15-16</th><th>16-17</th></tr></thead><tbody>'";
//Now loop through the result of the SQL statement that contains the modules associated with the selected course
$courses = array();
while($row = mysqli_fetch_array($result1)) {
$courses[] = $row;
} //while
for($d = 1; $d < 6; $d++){
$printday = $days[$d];
echo "<tr><td>" . $printday . "</td>";
for($t = 9; $t < 17; $t++) {
unset($course_row);
foreach($courses as $course){
if($course['Day'] == $d && $course['Time'] == $t){ //fix this area so that it moves along
$course_row .= $course['ModuleName'] . "<br/>\n " .$course['Location'] . "<br/>\n<br/>\n";
} //if
}
if(isset($course_row)){
echo "<td>" . $course_row . "</td>";
} else {
echo "<td> </td>";
} //else
} //for 2
echo "</tr>";
} //for 1

Dates between dates in table given different content

I have a scenario whereby I need to see if a date falls between a start date and an end date, then every table cell between those dates I need to fill with a word like continue (See picture below for example).
Pulling the data from the database and then comparing the start dates and end dates against an of array dates I am able to populate a table like the above image. The complications begin to arise when I try to add information to the cells between looping.
I used:
if(date("Y-m-d", strtotime($test->range[$i])) > $data['sData'] && date("Y-m-d", strtotime($test->range[$i])) > $data['eData']){
echo "<td class='col-md-6'>Continue</td>";
}
However, this didn't provide the output I was after.
My current code is:
$all = $db->prepare("SELECT * FROM `assignment` WHERE user_id = $user ORDER BY `sDate` ASC");
$all->execute();
$rows = $all->fetchAll(PDO::FETCH_ASSOC);
echo "<table class='table table-hover'><tr><td></td>";
for($i = 0; $i < count($test->range); $i++){
echo "<td class='col-md-6'>" . date("d-m-Y", strtotime($test->range[$i])) . "</td>";
}
echo "</tr>";
foreach($rows as $data){
echo "<tr><td>" . $data['name'] . "</td>";
for($i = 0; $i < count($test->range); $i++){
if($data['sDate'] === date("Y-m-d", strtotime($test->range[$i]))){
echo "<td class='col-md-6'>Start</td>";
}
if(date("Y-m-d", strtotime($test->range[$i])) > $data['sData'] && date("Y-m-d", strtotime($test->range[$i])) > $data['eData']){
echo "<td class='col-md-6'>Continue</td>";
}
if($data['eDate'] === date("Y-m-d", strtotime($test->range[$i]))){
echo "<td class='col-md-6'>End</td>";
}
echo "<td class='col-md-6'></td>";
}
}
echo "</table>"
How can I fill the table cells between start and end with the word continue?
Just use a helper variable?
foreach($rows as $data){
echo "<tr><td>" . $data['name'] . "</td>";
$started = false;
for($i = 0; $i < count($test->range); $i++){
if($data['sDate'] === date("Y-m-d", strtotime($test->range[$i]))){
echo "<td class='col-md-6'>Start</td>";
$started = true;
}
if($data['eDate'] === date("Y-m-d", strtotime($test->range[$i]))){
echo "<td class='col-md-6'>End</td>";
$started = false;
}
if($started){
echo "<td class='col-md-6'>Continue</td>";
}
echo "<td class='col-md-6'></td>";
}
}

Populate two columns HTML from MySQL [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I want to populate a two column HTML layout from a database using PHP. The records returned will be in date ordered descending, and I want to populate the columns so that the first record goes in column one and the next in column two then back to column one and so on.
I'm working on the theory that I should take the MySQL result and run through it splitting it into two arrays, by putting the first record in the first array and the second in the second array and so on then using those arrays to output to the columns.
The columns are defined as follows;
<div id="leftcol">
</div>
<div id="rightcol">
</div>
EDIT
while($row = mysql_fetch_array($result))
{
$lcol = $lcol + 1;
$vis = 0;
$uri = substr($row[1], 0, strpos($row[1], "&"));
$sql = "SELECT * FROM `readart` WHERE `url`=\"".$uri."\"";
$result2 = mysql_query($sql);
while($row2 = mysql_fetch_assoc($result2))
{
$vis = $row2['visits'];
}
$tit = myTruncate2($row[4], 91);
echo '<div class="newitem">';
echo '<img style="float:left;margin:6px;margin-right:20px;" src="newslogo/'.$row[2].'.png" width="40px" height="40px" />';
echo '<span id="header">'.$tit.'</span><br>';
//echo $row[6];
echo '<span id="date">'.date("D, j F g:i A", $row[6]);
if($vis > 0){echo ' - Viewed '.$vis.' times';}
echo '</span><hr>';
echo '<p id="textbody">';
echo $row[5];
echo '<br><br>Read More';
echo '</p><br></div>';
}
<?php
$row = array();
$rowCount = $mysql_row_count($result);
while ($row[] = mysql_fetch_array($result));
echo "<div idi\"leftcol\">";
for ($i = 0; $i < $rowCount; $i+=2)
echo $row[$i]; //Change this to whatever you want to echo or however you want to echo it
echo "</div>";
echo "<div idi\"rightcol\">";
for ($i = 1; $i < $rowCount; $i+=2)
echo $row[$i]; //Change this to whatever you want to echo or however you want to echo it
echo "</div>";
?>
EDIT
Here's what i came up with your code... I'm not sure if it will work right away since i haven't tested it. But I hope it gives you an idea of how to do it now.
<?php
function echoData($right, $row, $rowCount)
{
for ($i = $right; $i < $rowCount; $i += 2)
{
$lcol = $lcol + 1;
$vis = 0;
$uri = substr($row[$i][1], 0, strpos($row[$i][1], "&"));
$sql = "SELECT * FROM `readart` WHERE `url`=\"".$uri."\"";
$result2 = mysql_query($sql);
while($row2 = mysql_fetch_assoc($result2))
{
$vis = $row2['visits'];
}
$tit = myTruncate2($row[$i][4], 91);
echo '<div class="newitem">';
echo '<img style="float:left;margin:6px;margin-right:20px;" src="newslogo/'.$row[$i][2].'.png" width="40px" height="40px" />';
echo '<span id="header">'.$tit.'</span><br>';
//echo $row[6];
echo '<span id="date">'.date("D, j F g:i A", $row[$i][6]);
if($vis > 0){echo ' - Viewed '.$vis.' times';}
echo '</span><hr>';
echo '<p id="textbody">';
echo $row[$i][5];
echo '<br><br>Read More';
echo '</p><br></div>';
}
}
**Here you should put the query code**
$sql = "SELECT e.t.c e.t.c";
$result = mysql_query($sql);
$rowCount = mysql_num_rows(result);
$row = array();
while($row[] = mysql_fetch_array($result));
echo "<div id='leftside'>";
echoData(0, $row, $rowCount);
echo "</div>";
echo "<div id='rightside'>";
echoData(1, $row, $rowCount);
echo "</div>";
do this
$rightCol = "";
$leftCol = "";
$c = 0;
foreach($data as $box){
if ($c%2){
$leftCol.= $box;
} else {
$rightCol.= $box;
}
$c++;
}
Then for your html do this
<div id="leftcol">
<?= $leftCol ?>
</div>
<div id="rightcol">
<?= $rightCol ?>
</div>

Categories