Outputting dates in to a table padding missing dates in order - php

My array from a database looks like this:
$client[0]['Name'] = 'Foo';
$client[0]['Claim'][0]['year'] = 2013;
$client[0]['Claim'][1]['year'] = 2014;
$client[0]['Claim'][2]['year'] = 2015;
$client[1]['Name'] = 'Bar';
// no 2013!
$client[1]['Claim'][0]['year'] = 2014;
$client[1]['Claim'][1]['year'] = 2015;
// table headers are name, 2013, 2014, 2015...
foreach($client as $c) {
echo '<tr>';
echo '<td>' . $c['Client']['name'] . '</td>';
foreach($c['Claim'] as $claim) :
echo '<td>' . $claim['year'] . '</td>';
endforeach;
echo '</tr>';
}
Which works fine except when a $client is missing a year then the <td> are not balanced; causing my table to be incorrect.
My goal is to have each $claim['Year'] line up with the appropriate table heading.
I figured I could just add empty keys to each array and re-order them but that seems a bit unnecessary and wondered if there was a better way of doing it.
So an array might look
this would be ideal:
$years[null, 2014, 2015]
whereas currently it is
$years[2014,2015]
Hope this makes sense.

I am assuming you have a start and an end year that you want to display the claims for. Then if you replace the inner for loop with this I think it should work:
$x = 0; //Variable to keep track of what claim we are on.
//Loop through the years.
for($i=$start; $i<=$stop; $i++) {
//If there is a claim for this year, echo it and move on to the next claim.
if($c['Claim'][$x]['year'] == $i) {
echo '<td>' . $c['Claim'][$x]['year'] . '</td>';
$x++;
}
//If not, just echo an empty table cell.
else {
echo '<td></td>';
}
}
This only works if the claims are sorted by year. Please note that I have not tested the code.

Related

PHP : How to get a specific value of an array

I would like to get the id of a specific value in my phpmyadmin table.
So, I have got a table with 'id_cal' as an A.I. id, 'mois' representing the month with numbers (e.g 1 for january) and 'annee' representing the year. (see calendar table)
I am trying to set php variable for the month and the year and if they match the current month and year, I want to get this specific id.
I commented the php code where I am having my trouble, here it is :
<?php
include_once('config.php');
$m = idate('n');
$y = idate('Y');
echo $m; echo "\t"; echo $y; echo "<br>"; echo "<br>"; // The result of this is 7 2019
$reponse = $bdd->query('SELECT * FROM calendrier');
while($donnees= $reponse->fetch()){
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
echo $id_cal;
echo "\t";
echo $mois;
echo "\t";
echo $year;
echo "<br>";
}
// What I am trying to do :
if (($m = $mois) && ($y = $year)){ // If the month and the year are the current month/year
$i = $id_cal; // I want to put the id refering to the current month/year (in my phpmyadmin table) into a new variable
echo "<br>"; // and echo this variable (or use it in other ways)
echo $i; // BUT what I am echoing is 24 representing the number of values in my array
} // How can I only get 7 ? (in this exemple, since we are the 7/2019)
Here is what I am getting in my localhost : echo
I really don't understand why am I not having 7.
Also, I tried this instead of my while:
$donnees= $reponse->fetch();
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
// But in this cas I am having $i = 1, so it's the same problem.
Many thanks in advance for your response I am quite struggling with this.
It is because id_cal gets overwritten with the new value of id_cal in each iteration of your while statement.
To get the result you want, you could put the if inside the while statement...
while($donnees= $reponse->fetch()){
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
echo $id_cal;
echo "\t";
echo $mois;
echo "\t";
echo $year;
echo "<br>";
if (($m == $mois) && ($y == $year)){
$my_var_to_use_elsewhere = $id_cal;
}
}
echo "<br>";
echo $my_var_to_use_elsewhere;

how to create table with dynamic column using php

Suppose there is a number of item in array.which may be odd or even like I have an array which contain item from a to z Now I want to display that item in table . But As you know That There are 23 alphabets I want to display these alphabets in table which contains only 5 column in the last you got only three alphabets I want to display them in table . In the last I want that there should be three column not 5.
Here is my code i could not get that what should i do?
But the problem I faced in the below code is that the second loop is not correct.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$count= sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){
echo "<tr>";
for($j=0;$j<=5;$j++){
echo "<td>'".$arr[$j]."'</td>";
}
echo "</tr>";
}
echo "</table>";
?>
My approach uses array_slice to take out pieces of the source and build rows:
$arr=array('a','b','c','d','e','f','g','h');
$offset = 0;
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
$offset += $num_columns;
$row_html = '';
foreach($slice as $n) $row_html .= "<td>$n</td>";
$table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;
Live demo
Try below code. Declaring number of column required in a variable, so which can be changed any time. closing the tr tag when loop count is same as number of columns to be displayed.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
echo "<td>'".$arr[$r]."'</td>";
if($r + 1 == $columnLength ) {
echo "</tr>";
}
}
echo "</table>";
?>

php make html table rows equal

I am getting data from a my database. There is a admin panel also where people can add data to the database. The data gets on the page but some of the rows(<tr>) have less table data tags(<td>) than others. thus the table is not justified. Is there a way to add empty <td> to rows that need them? I have tried everything but i can't figure it out.
Picture on how the table looks at the moment:
The green numbers are the total sum of points but it's not clear because the table rows are jagged. How to fix tis?
If there is a jQuery solution that's also fine.
my code:
echo "<table class=\"zebra1\">";
echo "<th>N. </th>" . "<th>Team name: </th>" . "<th colspan=\"5\">Points: </th>" . "<th>Sum: </th>";
$numbering =1;
$query2 = $db->prepare("SELECT pisteet_1 As PIY, pisteet_2 as PIK, nimi As NIM, opisto As OPI, pisteet.kaupunki_id As KA FROM
pisteet INNER JOIN joukkueet ON joukkueet.id = pisteet.team_id INNER JOIN oppilaitokset ON oppilaitokset.opisto_id = joukkueet.opisto_id ORDER BY team_id ASC");
$query2->execute();
$results = $query2->fetchAll();
$tableD = array();
foreach ($results as $key) {
$tableD[$key['NIM']][] = array('PIY'=>$key['PIY'],'PIK'=>$key['PIK'],'KA'=>$key['KA'], 'OPI'=>$key['OPI']);
}
foreach($tableD as $teamN=>$values2){
//Echoing the Team name
echo "<tr class=\"all " . $values2[0]['KA'] . "\">";
echo "<td>" . $numbering . "</td>";
echo "<td>" . $teamN ."<span>" . $values2[0]['OPI'] ."</span></td>";
$sum1=0;
$sum2=0;
//Echoing the points
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
}
//Echoing the total sum of points
echo '<td class="Sum">'.$sum1.'/'.$sum2."</td>";
echo "</tr>";
$numbering ++;
}
echo '</table>';
I have a variable named: $colspancalculated that has the longest row: at the moment it stores the value 5.
Assuming you have a fixed number of columns (I assume this because you've got a colspan on your table header cell), you need to output the td elements as you are doing, or output blank cells if the records don't exist.
Consider something like this instead of your foreach:
// Echoing the points - as you mention in your comment, you've calculated
// the maximum column size as $colspancalculated - so you that as your upper limit
for($i = 0; $i < $colspancalculated; $i++) {
if(!isset($values2[$i]['PIY'])) {
// This record doesn't exist! Output a blank cell
echo '<td></td>';
continue;
}
// Otherwise, output the cell and do your calculations
echo '<td class="points">' . $values2[$i]['PIY'] . '/' . $values2[$i]['PIK'] . '</td>';
$sum1 += $values2[$i]['PIY'];
$sum2 += $values2[$i]['PIK'];
}
Instead of a foreach loop, use a for loop -- or, since you have to work with an iterator, anyway, just do:
$i = $numberOfColumnsLeftAtThisPointInYourScript
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
$i--;
}
while($i > 0){
echo '<td> </td>';
$i--;
}

Results are not showing correct in table

I am completely new in PHP so this question might be stupid. I could not find an answer after searching for hours.
I have made a query with a foreach loop but it does not show it right in the table I create. The part from the foreach show all in the field next to the last country.
I have tried to put the on all kind of other places but the result stays the same it does not come in the right column.
$query = "SELECT COUNT(landofbirth) as c, landofbirth FROM dog WHERE landofbirth IS NOT NULL GROUP BY landofbirth ORDER BY c desc LIMIT 1000";
$result = mysql_query($query) ;
$values = array();
$pct = array();
$total = 0;
while ($line = mysql_fetch_array($result)) {
echo "<tr><td>";
$values[$line[1]] = $line[0];
$total += $line[0];
echo "$line[1]</td><td> ";
echo "$line[0] </td><td>"; }
foreach($values as $key => $value) {
$pct[$key] = $value/$total ;
$count2 = $pct[$key] * 100;
$count = number_format($count2, 2);
echo "$count %"; }
echo "</td></tr>";
Your code is a bit garbled, perhaps from moving it around one too many times.
I always find it helpful to separate the display items one-by-one, even put them each on individual lines and away from the "calculation" code for better visuals when editing the code.
I'm not exactly sure if this is what you're looking for, but I think this display will be close (and/or easily modifiable):
while ($line = mysql_fetch_array($result)) {
$values[$line[1]] = $line[0];
$total += $line[0];
}
foreach($values as $key => $value) {
$pct[$key] = $value/$total ;
$count2 = $pct[$key] * 100;
$count = number_format($count2, 2);
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '<td>' . $count . '%</td>';
echo '</tr>';
}
Side Note (not answer specific)
It is recommended that you do not develop with the deprecated mysql extension in PHP. Instead, you should use the alternative and maintained mysqli or PDO extensions. Both are far more secure to use and provide beneficial features such as prepared statements!

Inserting array values into SQL

I randomized a set of questions using the following code:
for($i=0; $i < count($nwi); $i++)
$itemorder[$i] = $i;
shuffle($itemorder);
$_SESSION["itemorder"] = $itemorder;
A few pages later, a portion of the questions are presented:
for ($i=0; $i<40; $i++) {
if ($i % 10 ==0) echo $header;
echo '<tr class="';
if(in_array($itemlabel[$_SESSION["itemorder"][$i]], $errors)) echo 'skip';
elseif ($i % 2 == 0) echo 'even';
else echo 'odd';
echo '">';
echo '<td>' . ($i + 1) . ".</td><td>" . $itemtext[$_SESSION["itemorder"][$i]] . '</td>';
for ($j = 1; $j <= 6; $j++) {
echo "\n" . '<td';
if ($j == 6) echo ' style="background-color:#999;"';
echo '><input type="radio" name="';
echo $itemlabel[$_SESSION["itemorder"][$i]];
echo '" value="';
echo $j; //value of the input
echo '"';
if ($_POST[$itemlabel[$_SESSION["itemorder"][$i]]] == $j) echo " checked";
echo '></td>';
}
At the end of the survey, I am trying to put the answers to the questions (which should range in value from 1-8) into my SQL database:
"INSERT INTO surveydata
(id, agree_pppg_01,agree_pppg_02,agree_pppg_03,....
VALUES
('$_SESSION[id]', '$_SESSION[itemorder][0]',
'$_SESSION[itemorder][1]', '$_SESSION[itemorder][2]',
'$_SESSION[itemorder][3]',...
I am getting only zeros in my SQL database regardless of how I answer the questions. Any suggestions?
Well, first I don't see anything assigning anything to the session values, but the issue with your code is in this pattern: '$_SESSION[itemorder][1]'. First, I would make sure that MySQL is expecting a varchar there and not an int. If it is an int, good form would be to make sure it isn't quoted.
More importantly, though, when you have an associative array in PHP, you need to make sure PHP expects that.
This
$a = array("hi"=>array("world"=>0)); echo "$a[hi][world]";
Outputs
Array[world]
Put braces around the lookup to make sure it knows to treat it as an array, and then put quotes around all string indexes:
// note the braces and quotes
$a = array("hi"=>array("world"=>"here")); echo "{$a["hi"]["world"]}";
Outputs
"here"
But, I wonder if you wouldn't be better off just using implode:
$columns = implode(',', $_SESSION['itemorder']);
$query = "INSERT INTO surveydata
(id, agree_pppg_01,agree_pppg_02,agree_pppg_03,....
VALUES ('{$_SESSION["id"]}', $columns )";
I do feel obliged to point out that that system does not seem scaleable, and column names like agree_pppg_02 are not descriptive. You may want to go to the codereview stackexchange site to see if they can't offer tips on database design.

Categories