fetching data and trying to create a loop to determine lowest value - php

This is going to be a newbie question, so bear with me.
I have a database in which I fetch the data, I would like to create a for loop which will loop through the fetched data and will determine what the lowest time is. This is how my loop looks like: (take into consideration I only took the part out that seemed usefull to post, and $row['timePV'] is a time based value such as: 23:00)
$arrayCount = array();
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>";
echo $row['timePV'];
echo "</td>";
echo "</tr>";
array_push($arrayCount,$row['timePV']);
}
echo "</table>";
}
$c = 100000;
for ($i = 0; $i < sizeof($arrayCount); $i++) {
$arrayCount[$i];
if ($arrayCount[$i] < $c) {
$c = $arrayCount[$i];
echo $c;
} else {
//do something else
}
}
So what I want to achieve: Loop through the stored data and take out the lowest value and display that value, but it only displays all the values.
So my question: How can I make the loop in such way that it will take the lowest value and display it to me?

You don't have to do another loop to calculate lowesttime. You can do it in that while loop with checking previous and present timePv like following
//$timeExample=[["timePV"=>"11:30"],["timePV"=>"11:20"],["timePV"=>"13:30"]];//example of data
$lowestTime = null;//Deault defined it null
while ($row = mysqli_fetch_assoc($result)) {
//foreach($timeExample as $row){ //foreach for run example
if($lowestTime){
$lowestTime=min($lowestTime,strtotime($row['timePV']));//If not null we also get min lowerstTime from previous //and current one
}else{
$lowestTime=strtotime($row['timePV']);//It will work for only first iteration since $lowestTime will null in //first iteration
}
echo "<tr>";
echo "<td>";
echo $row['timePV'];
echo "</td>";
echo "</tr>";
}
echo date("h:i",$lowestTime);//11:20 example out

Related

PHP Tally Total from Entries in SQL - Best Practice Approach

not so much of a problem but more looking for best practice and the most efficient solution to an issue.
I have some code that reads all the lines for a userID in an sql table and can print them fine. Each row contains {Sales No. - D_No - Category1 - Category2 - Date}.
Now for each row I could have a massive number of if statements or etc to see if the category is equal to a field and then add 1 to a variable that acts as a tally as such. But I'm wanting something more efficient. Where it creates a variable of its own name and or adds to the existing variable of its name.
This is a summary of the pre-existing code:
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach ($row as $field => $value) {
foreach ($salesItemsArray as $saleItem){
if (strpos($value, '******CategoryNAME******') !== false){
}
}
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
So this code would essentially (possibly with a bit of editing) work if i replace the *****CategoryNAME***** with the actual category and repeat for each category or use an equivilant switch command (if php has one?). However if i could get the program to create a variable called $category Name each time it sees a new category and then add 1 to it each other time it would work for any category name and would be much more efficient and simpler.
Is this possible and any ideas how to implement?
Willing to rephrase parts if needed if confusing.
updated attempt at code :
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
foreach ($salesItemsArray as $saleItem){
if (strpos($value, $saleItem) !== false){
$foo[$saleItem] = $foo[$saleItem] + 1;
}
foreach ($foo as $saleTotal){
echo $saleTotal."<br/>".$foo[$saleTotal];
}
}
echo "<td>" . $value . "</td>";
Final code edit post hopefully
Thanks to comments i've gotten to this. However slight issue is it says there is 1 for every $foo[$saleItem] combination from echoing it out. As the database stands there should only be 1 item with 1 and everything else in the array and its variable 0...
while ($row = mysqli_fetch_assoc($individualResult)) {
echo "<tr>";
foreach ($row as $field => $value){
foreach ($salesItemsArray as $saleItem){
if (strpos($value, $saleItem) !== false){
if(isset($foo[$saleItem])) { $foo[$saleItem] += 1; } else { $foo[$saleItem] = 1;}
echo $saleItem;
}
foreach ($salesItemsArray as $saleTotal){
echo $foo[$saleTotal];
if ($foo[$saleTotal] > 0){
echo $saleItem."+".$foo[$saleTotal];
}
}
}
echo "<td>" . $value . "</td>";
echo "</tr>";
}

Splitting Long php generated HTML table?

I use a MySql query to select data from my DB and then print it in the form of a HTML Table. It works perfectly, fine but sometimes the table consists of hundreds of rows and the webpage looks incredibly akward. Is there a way to split the table side by side into 2 or 3 halves.
Present Output
Desired output
PHP
<?php
....
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
What would be the best way to achieve it?
Help would be appreciated.
You can use PHP to determine in your loop if the loop index is divisible by a certain number using something like this:
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
$rowCount = 1;
$numRows = count($results);
$maxRows = 12;
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
if($rowCount % $maxRows == 0 && $rowCount != $numRows) {
echo "</table><table class='dates' border='1'>";
}
$rowCount ++;
}
echo "</table>";
That's the basics of doing this. Basically in your loop you're testing each index to see if it's divisible by $maxRows, and if so then you're going to close your table and open a new one. You'll have to add the styling to place the tables side by side.
If you wanted to expand upon this concept you can set $maxRows to be an evaluation of $numRows. For instance if you wanted to split the items as close as possible to half in order to show just two tables, you could do... $numRows = count($results); $maxRows = round($numRows / 2);
Inspired by Robert Wade's answer:
<?php
....
echo "<h3>Classes attended :</h3>";
$i=0;
$maxRows=10;
foreach ($results as $dates) {
$a=$i/$maxRows == 0 ? "<table class='dates' border='1'>":"";
$b=$i/$maxRows == 0 ? "</table>":"";
echo $a;
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
echo $b;
$i++;
}
?>
At last, add some css style to the tables.
You can also use array_chunk() for splitting your results. Or instead of displaing a lot of tables next to each other you can make pagination and get only some range in your query. For example:
SELECT * FROM `clients` LIMIT 5, 10
Selects 10 rows beggining from row 5. Now, when you change your page, just change limit values.

How to do an HTML 'upward' rowspan

Here is the problem:
I need to know if there is a way to do an upward rowspan on a <th> element on a form.
I am reading some rows inside a DB that I need to put inside an html table.
I am doing something like:
echo "<table>";
while($result = $resultSet->fetch())
{
echo "<tr>";
echo "<td>$result['Name']</td>";
echo "<td>$result['Job']</td>";
echo "</tr>";
}
ehco "</table>";
First steps are easy until I needed to 'span' together two adjacent cells that contains the same value.
For exemple if someone have the same name but had two jobs I would like them to have something like :
echo "<tr>";
echo "<td rowspan='2'>$result['Name']</td>";
echo "<td>$result['Job']</td>";
echo "</tr>";
But I can't predict how many jobs someone have (except they all have at least one and that they are all in order).
exemple of record in MySQL table
Name/**/Jobs
Paul/**/Jobs1
Simon/**/Jobs23
Simon/**/Jobs45
Roger/**/Jobs67
(All simon's jobs are 'behind one another', they are grouped. If Paul had a second job it would be the second record in the table 'pushing' simons jobs down).
So I need to change the rowspan value of the first element to fit how many jobs that person have.
This is why I would need to know if it is possible to do a upward span because i could just display every on of them and count how many jobs each person have and do a rowspan that would merge the table cell upward.
It would certainly be easier then fetching every row in the DB then looping throught them all and checking how many jobs a person have to 'span' the cells now and then display them all and then skipping them. and so on.
Thanks
A situation like this calls for pre-processing. Like so:
$people = array();
while($result = $resultSet->fetch())
{
if( !isset($people[$result['Name']])) $people[$result['Name']] = array();
$people[$result['Name']][] = $result['Job'];
}
echo "<table>";
foreach($people as $name=>$jobs)
{
echo "<tr>";
echo "<td rowspan=\"".count($jobs)."\">".$name."</td>";
echo "<td>".array_shift($jobs)."</td>";
echo "</tr>";
foreach( $jobs as $otherjob)
{
echo "<tr><td>".$otherjob."</td></tr>";
}
}
echo "</table>";
Done!
What you're looking for doesn't exist in HTML. But you can do it like this:
$currName = $result['Name'];
echo "<tr>";
if($currName==$prevName)
{
echo "<td> </td>";
}
else
{
echo "<td>$result['Name']</td>";
}
echo "<td>$result['Job']</td>";
echo "</tr>";
$prevName = $currName;
Rather than using rowspan, just nest a table in the second column with all of the jobs for that person.
echo "<tr>";
echo "<td>$result['Name']</td>";
echo "<td>";
echo "<table>"
foreach($jobs as $job): //$jobs holds the job values for the current name
echo "<tr><td>";
echo $job;
echo "</td></tr>";
endforeach;
echo "</table>";
echo "</td>";
echo "</tr>";
Note: you will need to preprocess the result set to get a 2D array for this method (see answer from Niet the Dark Absol).

Breaking up a long line of values in a box

The array $carry_over returns a really long list of entries, too long for my printout page. I would love to make it in such a way that after 4 entries, it breaks and goes to the next line and breaks at the next four entries until all entries are in.
How can i do this?
Thanks
echo "<table class=\"altrowstable\" bgcolor = gold >\n";
$count = 0;
echo "<tr align= \"center\">\n";
$carry_over = array();
$score_count = mysql_numrows($query8);
echo "<td>"."Failed: ";
if($score_count !== 0){
while ($row8 = mysql_fetch_assoc($query8)) {
echo "<th>".$row8['course_code']."</th>";
if ( $count == 7 ){
echo "</tr>\n";
echo "</table>";
}
}
}
Update : Now only the first 7 entries are covered inside the table tags, the subsequent ones are outside the table tags. How can i put them in the tabke tags?
Thanks
Not sure if this is what you are looking for, but you could try:
$count = 0;
echo "<tr>";
while ($row8 = mysql_fetch_assoc($query8)) {
echo "<th>" . $row8['course_code'] . "</th>";
$count++;
if(count == 4) {
echo "</tr><tr>";
$count = 0;
}
}
echo "</tr>";
It looks like you're using a table for list data. Instead of using a <table>, you should be using a <ul> with <li> for each element. This can then be styled so that each li has display: inline-block;, for example.
I cannot tell what the table looks like from the code above, but you can put an iterator in to count to four then wrap. You also may want to check out Wordwrap

Adding extra table row

I'm stuck and can't figure this out.
I have this piece of code which is basically generating a table taking data from SQL cursor.
I need to add one extra table row <tr> (which will be filled with additional info) after each row. I've tried putting the new row in several places, but there is never any output data for it. This is someone else's code that I'm trying to modify.
$top_i=min($pagesize-1,$numrows-$start);
for($i = 0;$i<=$top_i;$i++) {
if (($i%2)==1)
echo "<tr class='saraksts_row0'>";
else
echo "<tr class='saraksts_row1'>";
$res=mssql_query("fetch absolute ".($start+$i)." from saraksts_cursor ");
$row=mssql_fetch_array($res);
$itemp = 0;
foreach($fields as $field) {
$key = $field[0];
if($field[2]) {
eval($field[2] );
}
$itemp++;
$val = ($row[$key] == "") ? " " : $row[$key];
// Get rid of right and left border, set topmost border
$st="";
if ($itemp==1)
$st.="border-left-style:none;";
if ($itemp==$numfields)
$st.="border-right-style:none;";
if ($i==$top_i)
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
$itemp = 0;
echo "</tr>\n";
}
The place where you want to add the extra row is after closing the first row and before the iteration moves to the next one. Note, it appears that you are doing some styling based on whether the row is odd or even. If you want this new row to have the same styling, I suggest you store the class you're applying to the preceding row so that you can also apply it to this row.
echo "</tr>\n";
echo "<tr><td>...</td><td>...</td></tr>\n"; /* Add the new row here */
}
...
$st.="border-bottom-style:solid;";
echo "<td style='$st'>$val</td>";
}
//Here we go
echo '<td style="blah">'.$yourotherinfo.'</td>';
$itemp = 0;
echo "</tr>\n";

Categories