<div class="row">
<?php
$r=mysql_query("SELECT * FROM advertisements WHERE $filter exposure!='0' AND `status`='2' AND (clicks_left_micro>0 OR clicks_left_mini>0 OR clicks_left_standard>0 OR clicks_left_extended>0) ORDER BY exposure DESC");
while($ar=mysql_fetch_array($r)):
echo "<div class='span4'> text here text here</div>";
endwhile;
?>
</div>
As you can see in the $r query, I am ordering by exposure. The exposure field can contain the numbers from 1-3. What I am trying to do is to create a new row for each exposure number. Example:
Advertisements that have exposure = 1, will be in the first row
Below that, will be advertisements that have exposure = 2
And last, there will be advertisements that have exposure = 3
The way it is now, the advertisements/span4 divs are just being echoed out next to each other. I want to sort them inside the while loop in <div class='row'></div>
What about something like this:
<div class="row">
<?php
$r=mysql_query("SELECT * FROM advertisements WHERE $filter exposure!='0' AND `status`='2' AND (clicks_left_micro>0 OR clicks_left_mini>0 OR clicks_left_standard>0 OR clicks_left_extended>0) ORDER BY exposure DESC");
$row1 = '';
$row2 = '';
$row3 = '';
while($ar=mysql_fetch_array($r)):
if($ar['exposure'] == 1)
$row1 .= '<span>Your code here for row 1</span>';
else if($ar['exposure'] == 2)
$row2 .= '<span>Your code here for row 2</span>';
else if($ar['exposure'] == 3)
$row3 .= '<span>Your code here for row 3</span>';
endwhile;
?>
<table>
<tr>
<td><?php echo $row1; ?></td>
<td><?php echo $row2; ?></td>
<td><?php echo $row3; ?></td>
</tr>
</table>
</div>
Of course you will have to adjust it to your needs, but this is the idea.
EDIT: As some other people have noticed, you should not use mysql_* functions anymore.
Since they are ordered by exposure, you can simply do :
$curExpo = null;
while( ... ) {
if( $curExpo !== $row['exposure']) {
create new row
$curExpo = $row['exposure'];
}
}
Related
I need to group all rows with matching roomcode. When I also group resort, it acts like it disables the grouping of roomcode and only gives me the results of the first row with a roomcode.
How can I group the resort column and still group matching roomcode columns? If I ungroup my resort code the query works correctly, but then I can't create separate divs for differing resorts.
The user is searching a date range, hence having multiple rows with the same roomcode, which fetches my points. This is why I am getting the sum of those points. My current way of grouping each resort for output HTML purposes is breaking that. I don't necessarily have to group the resorts, I just need each room at each resort created within its own DIV set. I have a basic example below.
Ideal HTML output
<div id="results">
<div id="resort resortcode">
<div id="roomresults">
<div id="room1"></div>
<div id="room2"></div>
</div>
</div>
<div id="resort2 resortcode2">
<div id="roomresults2">
<div id="room3"></div>
<div id="room4"></div>
</div>
</div>
</div>
This PHP code will group each set of results by resorts, but jacks up my price.
<?php
include("dbh.php");
mysqli_select_db($con, "checkavail") or die ("no database");
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$occupants = $_POST['occupants'];
$sqlCommand=
"SELECT
MIN(staydate) AS checkin,
MAX(staydate) AS lastnight,
MIN(available) AS available,
ra.resort AS resortcode,
ri.resort,
ri.room,
ri.roomcode,
ri.view,
SUM(ra.points*'20') AS price,
ri.sqfoot,
ri.description,
ri.bedding,
ri.amenities,
ri.sleeps,
ri.sleep_details,
ri.layout_img AS layoutimg,
ri.room_img AS roomimg,
ri.roomimg_thumb
FROM resort_availability AS ra
LEFT JOIN room_info AS ri ON (ra.room = ri.roomcode)
WHERE staydate >= '$checkin' AND staydate = '$checkout'
AND sleeps >= '$occupants'
GROUP BY ri.roomcode
ORDER BY ri.resort, points
";
$result=mysqli_query($con, $sqlCommand) or die(mysqli_error($con));
$data = array();
while($row = $result->fetch_assoc())
{
$itemName = $row["resort"];
$resortCode = $row["resortcode"];
if ( !array_key_exists($itemName, $data)) {
$data[$itemName] = array ();
}
$data[$itemName][] = $row;
}
foreach ($data as $itemName => $rows) {
echo '<div class="resort ' ,$resortCode , '">';
echo '<div class="resort_header"><h1>', $itemName, '</h1></div>';
foreach ($rows as $row){
if ($row['available'] > 0) {
$roomresult = '<div class="room_result roomavailable">';
$available = '<button class="available">BOOK NOW</button>';
$filtavail = 'available';
}
else {
$roomresult = '<div class="room_result roomsoldout" style="">';
$available = '<button class="soldout">SOLD OUT</button>';
$filtavail = 'soldout';
}
echo $roomresult;
echo '<div class="room_thumb"></div>
<div class="room_info"><h4>'
,$row['room'], '-' ,$row['view'] ,
'</h4></div>
<div class="price"><center><h3>','' ,$row['price'],'</h3>' , $available ,'</center></div></div>';
}
echo '</div>';
}
?>
This PHP code gives me accurate results but does not allow me to Create a div with results based on each resort IE, I don't know how to create a Header with the resort name, separating each set of rooms by resort as it is in the first example.
<?php
include("dbh.php");
mysqli_select_db($con, "checkavail") or die ("no database");
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$occupants = $_POST['occupants'];
$sqlCommand=
"SELECT
MIN(staydate) AS checkin,
MAX(staydate) AS lastnight,
MIN(available) AS available,
ra.resort AS resortcode,
ri.resort AS resort,
ri.room,
ri.roomcode AS roomcode,
ri.view,
SUM(ra.points) AS points,
ri.sqfoot,
ri.description,
ri.bedding,
ri.amenities,
ri.sleeps,
ri.sleep_details,
ri.layout_img AS layoutimg,
ri.room_img AS roomimg,
ri.roomimg_thumb
FROM resort_availability AS ra
LEFT JOIN room_info AS ri ON (ra.room = ri.roomcode)
WHERE staydate >= '$checkin' AND staydate < '$checkout'
AND sleeps >= '$occupants'
GROUP BY ri.resort, roomcode
ORDER BY ri.resort, points
";
$result=mysqli_query($con, $sqlCommand) or die(mysqli_error($con));
while($row = $result->fetch_assoc()) {
$pricecalc = ($row['points'])*20;
$price = number_format($pricecalc, 2);
//RESULTS BOX
if($row['available'] < "1"){
echo '<div id="'.$row['roomcode'].'-'.$row['resortcode'].'"','class="soldout roomresults room'.$row['resortcode'].'">';
}
if($row['available'] > "0"){
echo '<div id="'.$row['roomcode'].'-'.$row['resortcode'].'"','class="available roomresults room'.$row['resortcode'].'">';
}
//IMAGE BOX
echo '<div class="thumbnail"><img height="90" src="',$row['roomimg_thumb'],'">';
echo '</div>';
//ROOM DETAILS
echo '<div class="roomdetails">';
echo '<h4>'.$row['room'].' - '.$row['view'].'</h4>';
echo '<p>Sleeps: '.$row['sleep_details'].'</p>';
echo '<p class="clickfordetails">Click Image For Room Details</p>';
echo '</div>';
//PRICING BOX AND SUBMIT BUTTON
echo '<div class="price">';
echo '<h3>$',$price,'</h3>';
if ($row['available'] < "1"){
echo '<button type="button" class="soldoutbtn">SOLD OUT</button>';
}
if ($row['available'] > "0"){
echo '<button type="button" class="booknowbtn">BOOK NOW</button>';
}
echo '</div,$row>';
echo '</div></div>';
};
?>
Yes group by will give you the 1st record of the same group.
In my understanding , you want to show all the data but place all the records with the same roomcode together.
In that case, please change
GROUP BY ri.roomcode
ORDER BY ri.resort, points
to
ORDER BY ri.roomcode, ri.resort, points
I am a little bit confused about using while loop inside another. Everything is fine with the second loop but the first one only returns one value and it is the same.
$aukciono_laimetojai_while = mysql_query("SELECT id, user_id, date, win
FROM tb_auction_winners WHERE user_id = 206");
$aukciono_istorija_while = mysql_query("SELECT user_id, aukciono_id,
COALESCE(SUM(bid), 0) AS bid, date FROM tb_aukciono_istorija
WHERE user_id = 206 GROUP BY aukciono_id");
while ($r1 = mysql_fetch_assoc($aukciono_istorija_while)) {
while ($r2 = mysql_fetch_assoc($aukciono_laimetojai_while)) { ?>
<tr>
<td><?php echo $r2['date']; ?></td>
<td><?php echo $r2['win'] - $r1['bid']; ?> Eur</td>
<td>0 Eur</td>
<td>Plačiau <?php echo $r2['win'] . ' - ' . $r1['bid']; ?></td>
</tr>
<?php } } ?>
$aukciono_laimetojai_while returns:
click here
$aukciono_istorija_while returns: click here
Using these 2 while loops, the table looks like this: (www.i.stack.imgur.com/Os8Rx.png) (can't use more than 2 links, sorry)
Something is wrong with the second number (0.14 should not be the same in every row, only the first one) and it should return 3 rows ($r1 = mysql_fetch_assoc($aukciono_istorija_while) has 3 rows in the database). I do not know what is wrong here, using one while loop, everything is just fine. Could someone help me, please?
I have found the solution. I should use only one query in the while loop. Instead of this block of code:
$aukciono_laimetojai_while = mysql_query("SELECT id, user_id, date, win
FROM tb_auction_winners WHERE user_id = 206");
$aukciono_istorija_while = mysql_query("SELECT user_id, aukciono_id,
COALESCE(SUM(bid), 0) AS bid, date FROM tb_aukciono_istorija
WHERE user_id = 206 GROUP BY aukciono_id");
while ($r1 = mysql_fetch_assoc($aukciono_istorija_while)) {
while ($r2 = mysql_fetch_assoc($aukciono_laimetojai_while)) { ?>
<tr>
<td><?php echo $r2['date']; ?></td>
<td><?php echo $r2['win'] - $r1['bid']; ?> Eur</td>
<td>0 Eur</td>
<td>Plačiau <?php echo $r2['win'] . ' - ' . $r1['bid']; ?></td>
</tr>
<?php } } ?>
I should use this (1 query, 1 while loop):
$aukciono_laimetojai_ir_aukciono_istorija_while = mysql_query("
SELECT tai.aukciono_id tai_aukciono_id, taw.win taw_win, taw.date taw_date,
COALESCE(SUM(tai.bid), 0) tai_bid FROM tb_auction_winners taw
JOIN tb_aukciono_istorija tai ON taw.id = tai.aukciono_id
WHERE tai.user_id = $usid GROUP BY aukciono_id");
while ($r1 = mysql_fetch_assoc($aukciono_laimetojai_ir_aukciono_istorija_while)) { ?>
<tr>
<td><?php echo $r1['taw_date']; ?></td>
<td><?php echo $r1['taw_win'] - $r1['tai_bid']; ?> Eur</td>
<td>0 Eur</td>
<td class="placiau" data-aukciono-id=
"<?php echo $r1['tai_aukciono_id']; ?>">Plačiau</td>
</tr>
<?php } ?>
The code below has dynamic drop down list, that users chooses preferred brand and model, accordingly the table is generated in the webpage which results of brand, model and year . Now the code needs to group all the same year with different models and highlight them with set of different colors for each year accordingly. An expected results is attached as image.
// (___ & !!!) or (ALL & ___) or (ALL & ALL)
if ((!isset($_POST['model']) || ($_POST['brand'] == 'ALL' && empty($_POST['model']))) || ($_POST['brand'] == 'ALL' && $_POST['sip'] == 'ALL')) {
$query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` ORDER BY brand,model,year';
}
// (... & ...) or (... & ALL)
else if (!empty($_POST['brand']) && (empty($_POST['model']) || ($_POST['model'] == 'ALL'))) {
$query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` WHERE brand="'.$_POST['brand'].'" ORDER BY brand,model,year';
}
// (ALL & ...) or (ALL & notALL)
else if ($_POST['brand'] == 'ALL' && (!empty($_POST['model']) && $_POST['model'] != 'ALL')) {
$query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` WHERE model="'.$_POST['model'].'" ORDER BY brand,model,year';
}
else {
$query1 = 'SELECT DISTINCT brand,model,year FROM `carlist` WHERE brand="'.$_POST['brand'].'" AND model="'.$_POST['model'].'" ORDER BY brand,model,year';
}
//echo $_POST['brand'].'<br />'.$_POST['model'];
echo '<table border=1><tr><th>BRAND</th><th>MODEL</th><th>YEAR</th></tr>';
$result1 = mysqli_query($con, $query1);
while($row1 = mysqli_fetch_array($result1)){
//echo'<tr><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
$query2= 'SELECT DISTINCT brand,model,year, count(*) `number` FROM `carlist` WHERE brand="'.$_POST['brand'].'" GROUP BY `year` HAVING count(*) > 1';
$result2= mysqli_query($con, $query2);
$count=0;
while($row2 = mysqli_fetch_array($result2)){
if ( $row2['year'] == $row1['year']) {
$count=1;
}
//$intersect = array_intersect($row1,$row2);
//echo $intersect[1];
}
$bgcolor = "#FF8C00";
if($count==1){
echo '<tr style="background-color: tomato;" ><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
}else {
echo'<tr><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
}
}
echo '</table>';
Create function what generates random color
function getColor($year){
return '#'.substr(md5($year), 0, 6);
}
In your while loop
// Get color for current year
// Same years will be colored with same color
$bgColor = getColor($row1['year']);
// Print table row
echo '<tr style="background-color: '.$bgColor.';"><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
So your while loop will be
while($row1 = mysqli_fetch_array($result1)){
// Delete extra while and if condition
$bgColor = getColor($row1['year']);
echo '<tr style="background-color: '.$bgColor.';"><td>'.$row1['brand'].'</td><td>'.$row1['model'].'</td><td>'.$row1['year'].'</td></tr>';
}
NOTE: Your queries are vulnerable to SQL injection. Please see this answer on how to prevent it.
NOTE 2: Since your background colors are generated automatically, it may happen that text is not easily readable.
Method 1:
This won't need to do a nested loop. This first method will only work if your row is arranged by year.
/* DEFINE THIS VARIABLE FIRST BEFORE YOUR LOOP */
$yearstorage = ""; /* STORAGE FOR YOUR YEAR AND COMPARISON LATER */
$randomcolor = '#' . strtoupper(dechex(rand(256,16777215))); /* GENERATE RANDOM COLOR */
/* START OF YOUR LOOP */
while($row1 = mysqli_fetch_array($result1)){
$res = mysqli_query($con,"SELECT * FROM carlist WHERE year=".$row1['year']."");
if(mysqli_num_rows($res) > 1){ /* IF YEAR HAS ONLY ONE ROW */
$randomcolor = "#ffffff";
}
if(empty($yearstorage)){ /* START OF FIRST ROW */
?>
<tr style="background-color: <?php echo $randomcolor ?>;">
<?php
$storecolor = $randomcolor;
}
else if($yearstorage == $row1["year"]){ /* IF LAST YEAR ROW IS THE SAME AS THE CURRENT YEAR ROW */
?>
<tr style="background-color: <?php echo $storecolor ?>;">
<?php
}
else { /* IF THE LAST YEAR ROW IS NOT THE SAME WITH THE CURRENT YEAR ROW */
$randomcolor = '#' . strtoupper(dechex(rand(256,16777215))); /* GENERATE NEW RANDOM COLOR */
?>
<tr style="background-color: <?php echo $randomcolor ?>;">
<?php
$storecolor = $randomcolor;
}
$yearstorage = $row1["year"]; /* STORE THE CURRENT YEAR FOR COMPARISON ON THE NEXT LOOP */
?>
<td><?php echo $row1['brand']; ?></td>
<td><?php echo $row1['model']; ?></td>
<td><?php echo $row1['year']; ?></td>
</tr>
<?php
} /* END OF WHILE LOOP */
Method 2:
This second method will work even if your row is not arrange in year. Even if arranged by different column name which I would refer more to you.
You have to create a loop to get all the year distinctly, and store the color and year in an array, and compare and get them on your main loop.
No need to do a nested loop also. But two separated loop.
As you will notice, this code is also shorter than the first method.
If a year contains one row only, it will have a white background.
$counter = 0; /* DETERMINER OF THE COLOR TO BE USED LATER */
$res = mysqli_query($con,"SELECT DISTINCT year FROM carlist");
while($row = mysqli_fetch_array($res)){
$randomcolor = '#' . strtoupper(dechex(rand(256,16777215))); /* GENERATE NEW RANDOM COLOR */
/* STORE THE COLOR AND YEAR IN AN ARRAY */
$res2 = mysqli_query($con,"SELECT * FROM carlist WHERE year = ".$row['year']."");
if(mysqli_num_rows($res2) > 1){ /* IF YEAR IS USED MORE THAN ONCE */
$colorstorage[$counter] = $randomcolor;
}
else { /* ELSE, IT WILL HAVE A WHITE BACKGROUND */
$colorstorage[$counter] = "#ffffff";
}
$yearstorage[$counter] = $row['year'];
$counter = $counter + 1; /* INCREMENT COUNTER */
} /* END OF LOOP THAT STORES THE COLOR AND YEAR IN AN ARRAY */
/* START OF YOUR MAIN LOOP */
while($row1 = mysqli_fetch_array($result1)){
$key = array_search($row1["year"],$yearstorage);
?>
<tr style="background-color: <?php echo $colorstorage[$key]; ?>;">
<td><?php echo $row1['brand']; ?></td>
<td><?php echo $row1['model']; ?></td>
<td><?php echo $row1['year']; ?></td>
</tr>
<?php
} /* END OF YOUR MAIN LOOP */
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 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.