I am getting some values from a mysql database, but the values in the db are not in order. I want to order the days of the week as SUN, MON, TUE, etc. and display the corresponding values from the db table. I am currently displaying the values from the db without sorting. And I add the values to an array. How can I sort and show the values in an html table? This is my code
<?php
$q3 = mysqli_query($link,"SELECT * FROM stores_op_hours WHERE Store_Id='$stid' ");
?>
<table class="table ophours">
<thead class="thead-inverse">
<tr><th>Day</th><th>Open Time</th><th>Close Time</th></tr>
</thead>
<?php
$myarray = array();
while($rw = mysqli_fetch_array($q3)){
$day = $rw['Day_Name'];
$op = $rw['Open_Time'];
$cl = $rw['Close_Time'];
//$day = strtoupper($day);
$myarray[] = array("day" => $day, "open" => $op, "close" => $cl);
?>
<tbody>
<tr><td><?php echo $day; ?></td><td><?php echo $op; ?></td><td><?php echo $cl; ?></td></tr>
</tbody>
<?php
}
?>
</table>
What you could do is the ORDER BY FIELD(id,3,2,1,4) solution. Then in the query you would specify the sort order for the Day_Name field, like so:
$q = sprintf("SELECT * FROM stores_op_hours WHERE Store_Id=%d
order by field(Day_Name,'SUN','MON','TUE','WED','THU','FRI','SAT')",(int) $stid);
So the final edit (thanks to #Erik Dohmen) should look like:
$q = sprintf("SELECT * FROM stores_op_hours WHERE Store_Id=%d
order by field(Day_Name,'SUN','MON','TUE','WED','THU','FRI','SAT')",
(int) $stid);
$q3 = mysqli_query($link,$q);
Related
How do I count duplicate "itemid" entries from MySQL. The code below exports results in MySQL, but I want to count the total of each duplicate "itemid".
Example:
output(122,133,122,122,133,188). 122=3, 133=2, 188=1.
if(isset($_POST['daily']) && isset($_POST['reportdate'])){
global $conn;
$date = $_POST['reportdate'];
$sql = $conn->prepare("SELECT * FROM issues WHERE date='$date'");
$sql->execute();
$output .='
<table class="table" bordered="1">
<tr>
<th class="green">SAPCODE</th>
<th class="green">DATE</th>
<th class="green">DESCRIPTION</th>
<th class="green">QUANTITY</th>
<th class="green">UNIT</th>
<th class="green">ISSUED TO</th>
</tr>
';
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$perstat->getID($row['empid']);
$stock->getItemByID($row['itemid']);
$time = strtotime($row['date']);
$row['date']= date("d-M-y", $time);
$output .='
<tr>
<td>'.$row['itemid'].'</td>
<td>'.$row["date"].'</td>
<td>'.$stock->description.'</td>
<td>'.$row["qty"].'</td>
<td>'.$stock->unit.'</td>
<td>'.$perstat->pats.'</td>
</tr>
';
}
$output .='</table>';
header("Content-Type: application/xls");
header("Content-Disposition:attachment; filename=PPE Issuance report .xls");
header("Pragma: no-cache");
header("Expires: 0");
echo $output;
}else{
header("Location:issuelist.php");
}
I may infer that there is a column "itemid" in your issues table but I don't know that there is enough information in what you posted to be of help.
Here is how you would find duplicates
Finding duplicate values in MySQL
You should try this:
SELECT CONCAT(itemid,count(itemid)) FROM issues WHERE date='$date'" GROUP BY itemid
SELECT COUNT(itemid) FROM issues WHERE date='$date' GROUP BY itemid
You could add each itemID to an array as an index and keep count of them as you go through your results from your query.
For example (code commented for more explanation):
$item_id_count = array(); // Declare an empty array to keep count of itemIDs
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$perstat->getID($row['empid']);
$stock->getItemByID($row['itemid']);
$time = strtotime($row['date']);
$row['date']= date("d-M-y", $time);
$output .='<tr>
<td>'.$row['itemid'].'</td>
<td>'.$row["date"].'</td>
<td>'.$stock->description.'</td>
<td>'.$row["qty"].'</td>
<td>'.$stock->unit.'</td>
<td>'.$perstat->pats.'</td>
</tr>';
// Add itemID index into array with value of 0 if it does not exist
if(!isset($item_id_count[$row['itemid']])){
$item_id_count[$row['itemid']] = 0;
}
// Increment the value of the itemID index in array when it does exist
$item_id_count[$row['itemid']]++;
}
// Print out each itemID with its count from the array.
foreach($item_id_count as $itemID => $itemIDCount){
echo $itemID ." - " . $itemIDCount
}
Finally I found it
$sql = $conn->prepare("SELECT * ,itemid,count(*) AS total_records FROM issues WHERE date='$date' GROUP BY itemid");
Hey guys I need your help, I have this table
and I want to shows like this FIDDLE, really I don't know how to do this because sometimes just exist two columns(prov_name ) and sometimes exist more that two rows please help me if you can !
Hope you understand me. Thanks so much !
In this way I can be able to select data from Joomla.
$db =& JFactory::getDBO();
$query = 'SELECT prov_name FROM provprices where CA_id = '.$CA_id;
$db->setQuery($query);
$result = $db->loadObjectList();
$prov_name = $result[0];
echo $prov_name->prov_name;
First off, in order for your data to be presented like that obviously it must be grouped accordingly.
The first row is, the prov_name's, so you can use GROUP BY or you cal also do it in PHP. Based of the sample data, it should have from 1 to 6.
Then the second row is just a simple unitval and totval according to how many prov_name's.
Third is the and the rest is the grouping of the values. See Example:
$db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8', 'USERNAME', 'PASSWORD');
$data = array();
$results = $db->query("SELECT * from YOUR_TABLE_NAME");
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
$data[$row['prov_name']][] = $row;
}
$keys = array_keys($data);
$size = count($keys);
$vals = array();
// grouping:
// if there are six (cam1 to cam6)
// then group them by cam1, ... to cam6, then repeat until theres no more left
while(count($data) > 0) {
foreach($keys as $key) {
if(!empty($data[$key])) {
$vals[] = array_shift($data[$key]);
} else {
unset($data[$key]); // remove them if empty
}
}
}
$vals = array_chunk($vals, $size); // split them by how many prov_names
?>
<table border="1" cellpadding="10">
<!-- PROV NAMES -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<th colspan="2"><?php echo "prov_name $x"; ?></th>
<?php endfor; ?></tr>
<!-- unitval totvals -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<td>unitval</td><td>totval</td>
<?php endfor; ?></tr>
<!-- the grouped values -->
<?php foreach($vals as $val): ?>
<tr>
<?php foreach($val as $v): ?>
<td><?php echo $v['unitval']; ?></td>
<td><?php echo $v['totval']; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
I think you must do this first,
try looping to show prov_name in horizontal,
and then you fetch again in query with
"SELECT * FROM table_test where prov_name = '$prov_name'"
in Variable $prov_name you must have a value with CAM2 or CAM3 .etc
sorry just a logic :)
I am using the code below to generate a simple HTML table that displays the next 90 calendar days. Each day is a row in this simple table.
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td></tr>\n";
}
echo "</table>";
Also, I have a MySQL table with the following fields:
event varchar(1000)
datescheduled date
How can I make a second column in the aforementioned HTML table, containing "event" from the MySQL table, matched by date?
This can be tackled in numerous ways. Consider this example:
PHP
<?php
$con = mysqli_connect("localhost","dbuser","dbpass","database");
$query = mysqli_query($con, "SELECT * FROM event");
// First build the array of events, put the dates in keys, then the values as events
$events = array();
while($result = mysqli_fetch_assoc($query)) {
$events[$result['datescheduled']] = $result['event'];
}
?>
// Structure should be something like this:
Array
(
[2014-05-02] => Day of lorem
[2014-06-02] => Day of ipsum
[2014-07-02] => Day of days
)
HTML
<!-- the compare selected values on the current loop, check its keys -->
<?php $now = time(); ?>
<table border="1" cellpadding="10">
<?php for($i=0;$i<90;$i++): ?>
<?php $thisDate = date("Y-m-d", $now + ($i*86400)); ?>
<tr>
<td><?php echo $thisDate; ?></td>
<td><?php echo array_key_exists($thisDate, $events) ? $events[$thisDate] : ''; ?></td>
</tr>
<?php endfor; ?>
</table>
$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
$thisDate = date("d/m/Y",$now + ($i*86400));
echo "<tr><td>".$thisDate."</td>";
$result_set = mysql_query("SELECT event FROM eventTable WHERE datescheduled = STR_TO_DATE('{$thisDate}','%d/%m/%Y')'",$connection);
$result = mysql_fetch_assoc($result_set);
echo "<td>{$result['event']}</td></tr>\n";
}
echo "</table>";
Its worth noting that you will need to use a string to date function in mysql depending on how the date is stored.
Edit: in case you need further hand holding, here is the STR_TO_DATE function done for you.
STR_TO_DATE('{$thisDate}','%d/%m/%Y')
I have edited my code above to reflect this as to not strain your brain.
Even tossed in some screenshots of the table and the output, just because you were kind of an ass in your comment. With 5 years of experience i would have thought you would know how to echo out a simple table like this, or at the very least, have a little common courtesy when someone tries to help you.
I have the following two table structures in MySQL, which record details of a conference call and those participants that joined it:
Table: conference:
conference_sid, date_created, date_completed, RecordURL, PIN
*date_created and *date_completed are timestamps
Table: participants:
conference_sid, call_sid, call_from, name_recording
I want to output a simple table, that displays the following results for each conference_sid as a separate row:
<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<tr id="conference_sid">
<td>date_created</td>
<td>duration: [date_completed - date_created in h/mm/ss]</td>
<td>
<li>call_from [for all participants in that conference_sid]
<li>call_from...
</td>
<td>
Call recording
</td>
</tr>
<tr id="conference_sid">
...
</tr>
</tbody>
</table>
I only want this table to show relevant results for conferences that have the same PIN as the user's Session::get('PIN')
You can combine the participants using GROUP_CONCAT
SELECT
conf.conference_sid,
date_created,
TIMEDIFF(date_completed, date_created) AS duration,
conf.RecordURL,
conf.PIN,
GROUP_CONCAT(pid SEPARATOR ",") AS pid,
GROUP_CONCAT(call_sid SEPARATOR ",") AS call_sid,
GROUP_CONCAT(call_from SEPARATOR ",") AS call_from,
GROUP_CONCAT(name_recording SEPARATOR ",") AS name_recording
FROM
conference conf
LEFT OUTER JOIN
participants p ON p.conference_sid = conf.conference_sid
WHERE
conf.PIN = 123
GROUP BY conf.conference_sid
Refer SQLFIDDLE and MySQL documentation about TIMEDIFF.
Now the application logic will be
<?php
$pin = 123;
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare(
'SELECT
conf.conference_sid,
date_created,
timediff(date_completed, date_created) AS duration,
conf.RecordURL,
conf.PIN,
GROUP_CONCAT(pid SEPARATOR ",") AS pid,
GROUP_CONCAT(call_sid SEPARATOR ",") AS call_sid,
GROUP_CONCAT(call_from SEPARATOR ",") AS call_from,
GROUP_CONCAT(name_recording SEPARATOR ",") AS name_recording
FROM
conference conf
LEFT OUTER JOIN
participants p ON p.conference_sid = conf.conference_sid
WHERE
conf.PIN = :pin
GROUP BY conf.conference_sid');
$stmt->bindParam(':pin', $pin);
?>
<table border="1">
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<?php
$stmt->execute();
while ($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['date_created']; ?></td>
<td><?php echo $row['duration']; ?></td>
<td>
<table border="1">
<thead>
<th>call_sid</th>
<th>call_from</th>
<th>name_recording</th>
</thead>
<tbody>
<?php
$length = count(explode(',', $row['pid']));
$call_sid = explode(',', $row['call_sid']);
$call_from = explode(',', $row['call_from']);
$name_recording = explode(',', $row['name_recording']);
for ($i=0; $i < $length; $i++) {
?>
<tr>
<td> <?php echo $call_sid[$i]; ?> </td>
<td> <?php echo $call_from[$i]; ?></td>
<td> <?php echo $name_recording[$i]; ?> </td>
<tr>
<?php
}
?>
</tbody>
</table>
</td>
<td>
<a href="<?php echo $row['RecordURL']; ?>">
Call recording</a>
</td>
</tr>
<?php
}
?>
</tbody>
You will get the result set with comma(,) separated values in pid, call_sid, call_from, and name_recording. You can convert this string to array using explode.
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
I won't do the PHP part, as I am not that knowledgeable in PHP, but here is the SQL:
SELECT *
FROM `conference`, `participants`
WHERE `conference`.PIN = $PIN AND
`participants`.conference_sid = `conference`.conference_sid
This will return rows with the information from conference and the participants of those conferences, joined into one row.
The following query will give you the information you need to display:
SELECT c.conference_sid
, c.date_created
, timediff(c.date_completed, c.date_created) AS duration
, p.call_from
, p.name_recording
, c.RecordURL
FROM conference c
JOIN participants p
ON c.conference_sid = p.conference_sid
WHERE c.PIN = :PIN
ORDER BY c.conference_sid
You will need to process the results with a nested loop. The outer loop should advance each time the conference_sid changes. The inner loop will display each element of the participants list for that conference.
This will be my take on it, it uses 2 separate queries to keep the data kinda separated. I use fetchAll() for brevity but this could have performance issues, luckily this can be accomodated. I didn't put any error checking, if you want it or you have questions, please ask
<?php
// assume $db is a PDO connection to the database
/* #var $db PDO */
$q = 'SELECT conference_sid, date_created, date_completed, RecordURL, PIN'
.' FROM conference';
// we need these
$conferences = $db->query($q)->fetchAll(PDO::FETCH_CLASS,'stdClass');
// let's group them as CSV, and concatenate the contents with ":"
$q = 'SELECT conference_sid,GROUP_CONCAT(CONCAT_WS(":",call_from,name_recording)) AS parts '
.' FROM participants GROUP BY conference_sid';
$conf_parts = array();
foreach ($db->query($q)->fetchAll(PDO::FETCH_CLASS,'stdClass') as $parts) {
// save the participants as an array, their data is still joined though
$conf_parts[$parts->conference_sid] = explode(',',$parts->parts);
// their contents will be exploded later
}
?>
<table>
<thead><th>Date</th><th>Duration</th><th>Participants</th><th>Recording</th></thead>
<tbody><?php foreach ($conferences as $conference) {
$csid = $conference->conference_sid;
// http://stackoverflow.com/questions/3108591/calculate-number-of-hours-between-2-dates-in-php
// Create two new DateTime-objects...
$date1 = new DateTime($conference->date_completed);
$date2 = new DateTime($conference->date_created);
// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);
?><tr id="<?php echo $csid; ?>">
<td><?php echo $conference->date_created; ?></td>
<td><?php echo $diff->format('H/i/s'); ?></td>
<td>
<ul><?php foreach ($conf_parts[$csid] as $participant) {
// we have each participant for this conference call
list ($call_from, $name_recording) = explode($participant,':');
// and now we have the required data from each participant
?><li><?php echo $call_from; ?></li><?php
} ?></ul>
</td>
<td>
Call recording
</td>
</tr><?php
} ?></tbody>
</table>
In this particular contex I prefer to use two separated queries. Here's how I would do it:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Could not connect to db';
exit;
}
$stmt_conferences = $db->prepare(
'SELECT
date_created,
timediff(date_completed, date_created) AS duration,
RecordURL,
conference_sid
FROM
conference
WHERE
PIN=:pin');
$stmt_conferences->bindParam(':pin', $pin);
$stmt_participants = $db->prepare(
'SELECT
name_recording,
call_from
FROM
participants
WHERE
conference_sid=:confsid');
$stmt_participants->bindParam(':confsid', $confsid);
?>
<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>
<?php
$pin = 1; /* get your PIN here */
$stmt_conferences->execute();
while ($row = $stmt_conferences->fetch()) {
?>
<tr>
<td><?php echo htmlspecialchars($row['date_created'], ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($row['duration'], ENT_QUOTES); ?></td>
<td>
<?php
$confsid = $row['conference_sid'];
$stmt_participants->execute();
while ($participant = $stmt_participants->fetch()) {
?>
<li><a href="<?php echo htmlspecialchars($participant['name_recording'], ENT_QUOTES); ?>">
<?php echo htmlspecialchars($participant['call_from'], ENT_QUOTES); ?>
</a>
<?php
}
?>
</td>
<td>
<a href="<?php echo htmlspecialchars($row['RecordURL'], ENT_QUOTES); ?>">
Call recording</a>
</td>
</tr>
<?php
}
?>
</tbody>
Please notice that you have to add some code to handle errors and to correctly escape all data you echo (can you really trust your database?). Also element IDs should be unique within the entire document, you can have just one id="conference_sid" in your page. Use classes instead.
Edit
If you can really trust your database, then you can just output the contents of a field with code like this:
<?php echo $row['call_from']; ?>
but what happens if RecordURL contains for example the following string?
<script>alert("I am injecting some code....");</script>
It will happen that some unwanted code will be injected in your page, so it is always better yo use a safe function like htmlspecialchars() every time you need to echo some output:
<?php echo htmlspecialchars($row['call_from'], ENT_QUOTES); ?>
this way, any unwanted code won't be harmful.
I also added a basic TRY/CATCH construct to handle errors.
Hope this helps!
First, we need to get our result.
$vPIN = $_SESSION['PIN']; // or however you get your user's pin from session
$vQuery = "SELECT * FROM conference AS a LEFT JOIN participants as B USING (conference_sid) WHERE a.PIN='$vPIN'";
$oResult = $oDB->execute($vQuery);
$aRows = $oResult->fetchAll(PDO::FETCH_ASSOC);
note the prefixes: $v if for a simple variable, $o represents a ressource (which I like to think of as an object), $a represents an array. It's just for my mental sanity.
so now, we have an array, probably very big, containing every single row in the conference table times every corresponding row in the participants. Sweet, now let's build an array with some meaning in it.
foreach($aRows as $aRow) // maybe a bit confusing but the 's' changes everything: all rows vs one row
{if (!isset($aConferences[$aRow['conference_sid']]['infos']))
{$aConferences[$aRow['conference_sid']]['infos']['date_created'] = $aRow['date_created'];
$aConferences[$aRow['conference_sid']]['infos']['date_completed'] = $aRow['date_completed'];
$aConferences[$aRow['conference_sid']]['infos']['record_url'] = $aRow['RecordURL'];
$aConferences[$aRow['conference_sid']]['infos']['pin'] = $aRow['PIN'];}
$aConferences[$aRow['conference_sid']]['participants'][] = $aRow['call_from'];}
so what happens here is that for each row, if the infos for corresponding conference_sid haven't been set, they will be, and then we create a list from 0 to x of each call_from for that conference. print_r of that array with dummy values:
[1627]['infos']['date_created'] = 2013-11-26
['date_completed'] = 2013-11-29
['record_url'] = 'http://whatever.com'
['PIN'] = 139856742
['participants'][0] = Bob
[1] = gertrude
[2] = Foo
[8542]['infos']['date_created'] = 2013-12-01
['date_completed'] = 2013-12-02
['record_url'] = 'http://whateverelse.com'
['PIN'] = 584217
['participants'][0] = Family Guy
[1] = aragorn
[2] = obama
[3] = Loki
so here is a nice array with which we can build a html table! let's do that
$vHTML = '<table>
<thead>
<th>Date</th>
<th>Duration</th>
<th>Participants</th>
<th>Recording</th>
</thead>
<tbody>';
foreach ($aConferences as $conference_sid => $aConference) // notice the s and no s again
{$vHTML.= '<tr id="' . $conference_sid . '">';
$vDateCreated = $aConference['infos']['date_created'];
$vDateCompleted = $aConference['infos']['date_completed'];
$vHTML.= '<td>' . $vDateCreated . '</td>';
$vHTML.= '<td>' . date('Y-m-d',(strtotime($vDateCompleted) - strtotime($vDateCreated))) . '</td>'; // you might have to debug that date diff for yourself.
$vHTML.= '<td><ul>'; // here a foreach for the participants
foreach ($aConference['participants'] as $call_from)
{$vHTML.= '<li>' . $call_from . '</li>';}
$vHTML.= '</ul></td>';
$vHTML.= '<td>' . $aConference['infos']['record_url'] . '</td>';
$vHTML.= '</tr>';}
$vHTML.= '</tbody></table>';
so here: for each conference create a table row with the infos, then for each participant, add a list item within the list. comment if you wish for any precision.
oh, and don't forget to do something with $vHTML. like echo $vHTML :)
I have been working on trying to get a bunch of data to work in a table structure displayed neatly using PHP, and I must say I am having a difficult time. I have finally been able to call the columns so that in case I add a field it will always add it in my table, and I hope for this to be very easily managed. However, when I initially set up the table, I put it in a random order. Now when I come use the DESCRIBE table it gives them to me in exact order, and I cannot find a way to organize them better. It would not make sense to say have month/year at the end of the database for my form that I have.
<?php
require 'connect.php';
?>
<h3>Monthly Finances | Add New Month </h3>
<table border="1" bordercolor ="#000000">
<tr>
<?php
$columns = "DESCRIBE `month` ";
if($query_run_columns = mysql_query($columns)){
$columnNames = array();
while($column = mysql_fetch_assoc($query_run_columns)){
echo '<th>'.$column['Field'].'</th>';
}
}else{
echo'sql error';
}
?>
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
while($row = mysql_fetch_assoc($query_run)){
$rent = $row['rent'];
$electric = $row['electric'];
$cable = $row['cable'];
$cellphone = $row['cellphone'];
$renters = $row['renters'];
$month = $row['month'];
$year = $row['year'];
echo '<tr>';
echo '<td align="center">'.$month.'</td>';
echo '<td algin="center">'.$year.'</td>';
echo '<td align="center">'.$rent.'</td>';
echo '<td align="center">'.$electric.'</td>';
echo '<td align="center">'.$cable.'</td>';
echo '<td align="center">'.$cellphone.'</td>';
echo '<td align="center">'.$renters.'</td>';
echo '</tr>';
}
}else{
echo 'query error';
}
?>
<br>View by month
</table>
<form action="index.php" method="GET">
<select name="months" value="all">
<?php
$gathermonths = "SELECT `month`, `year` FROM `month";
if($query_month_selector = mysql_query($gathermonths)){
while($month_row = mysql_fetch_assoc($query_month_selector)){
$month = $month_row['month'];
$year = $month_row['year'];
echo '<option value="'.$month.' '.$year.'">' .$month.' '.$year.'</option>';
}
}
echo $_GET['months'];
?>
<input type="submit" value="View Selected Date"></input>
</select>
</form>
My code is very far from complete, or orderly but I have been slacking on this project and I will clean it up more when I have more time. But if you could please give me a hand on an efficient organizational method that would be appreciated.
Do your tables contain an index/id?
You can easily order them in ascending/descending by "ORDER BY"
ALTER TABLE `table_name` ORDER BY `id`
Note default ORDER BY is in ascending order. Put DESC at the end if you want descending.
If you want your mysql query to output results in a nice ordered fashion, you can also use ORDER BY in the query:
$gathermonths = "SELECT `month`, `year` FROM `month` ORDER BY `month` DESC";
There is also GROUP BY functions in case you wanted to group your results by month:
$gathermonths = "SELECT `month`, `year` FROM `month` GROUP BY `month`";
Instead of the DESCRIBE query, you could use mysql_fetch_field. Then columns will always be in the same order you have on your SELECT:
<?php
$gatherdata = "SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month` ";
if($query_run = mysql_query($gatherdata)){
// Loop the columns to build the table headers
echo '<table>';
echo '<tr>';
while ($i < mysql_num_fields($query_run)) {
$field = mysql_fetch_field($query_run, $i);
echo '<th>' . $field->name . '</th>';
$i++;
}
echo '</tr>';
// Your current data loop
while($row = mysql_fetch_assoc($query_run)){
// (...)
}
echo '</table>'
}
?>
Since you're already specifying which columns you're fetching, simply output the column headers explicitly rather than querying the database.
Contrariwise, if you want to abstract the HTML table generation code so that it works with arbitrary SQL tables (thus separating data access from display), record the column names as you generate the column headers in an array, then iterate over this array when outputting rows. You can also do away with the $rent = $row['rent']; assignments, as they gain you nothing. Using PDO:
/* data access */
$finances = $db->query('SELECT `month`, `year`,`rent`,`electric`,`cable`,`cellphone`,`renters` FROM `month`');
$columns = array();
for ($i = 0; $i < $finances->columnCount(); ++$i) {
$meta = $finances->getColumnMeta($i);
$columns[$meta['name']] = ucwords($meta['name']);
}
/* data display. Note this is completely independent of the type used to store
the colum & row data. All that matters are that $columns and $finances are
Traversable
*/
?>
<table>
<thead>
<tr>
<?php foreach ($columns as $name => $label): ?>
<th><?php echo $label ?></th>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach ($finances as $monthly): ?>
<tr>
<?php foreach ($columns as $name => $label): ?>
<td><?php echo $monthly[$name]; ?></td>
<?php endforeach ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Error handling and abstraction into modules left as an exercise.