How to display data in multiple columns with php? - php

Hi I need to build a table with two columns from a mySQL table.
Here is what i have now:
<table>
<?php
$sql = "SELECT field1, field2 FROM tblX"
$result = mysql_query($sql) or die("\nError Retrieving Records.");
while($row = mysql_fetch_array ($result, MYSQL_ASSOC)){?>
<tr>
<td>
<?=$row['field1']?> - <?=$row['field2']?>
</td>
</tr>
<?php }?>
</table>
This will create one column table like so:
1
2
3
4
5
I need the table to be in two columns like this:
1 4
2 5
3
Is this possible if it is how do I do that?

This should do what you want, if you insist on a table.
Get the mid point:
$mid = ceil(mysql_num_rows($result)/2);
Get an array:
while( $row = mysql_fetch_row($result) ) {
$list[] = $row; }
Output the rows:
for( $i = 0; $i < $mid; $i++ ) {
$itemOne = $list[$i];
$itemTwo = $list[$i + $mid];
// echo them in two tds.
}
I agree with marco, though. You could just as easily list items one to $mid in one div, then $mid to the end in another, and use CSS to float the divs side-by-side. Using tables for formatting purposes is evil.

read all values in a list, get the half value, write a loop that shows [i] and [i+halfvalue] together

Your question is unclear, but it sounds like you want to rearrange how the data is displayed and don't want the standard row-by-row output. You should probably do this manually if your order requires a method that cannot be looped through.
You should arrange the table BEFORE you output it, then once you've got everything all tidy, simply output the code.

Must it be in tables?
If you have in it a div and you have it set so that 3 items can contain in the height.
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
#container { height: 300px; }
.item { height: 100px; }
You can use some css floating to solve that combined with some padding and margin.

Related

Stumped with table formatting

If you remember me from asking the 20+ questions yesterday, I'm still awake and still at it. I'd like to inform anyone who cares I've made GREAT progress.
What I'm trying to figure out now is how to create a minimum about of rows for a table to have. The reason being is if the Table on my page doesn't have exactly 12 rows, it looks bad. The problem is there won't always be 12 rows worth of data in the SQL Database, so I need to find a way to make it so if there's not 12 results it fills in the table with a character of choice, probably "--"
Also, I'm trying to figure out how to create pages for the table. I haven't done any research on that one yet and it's not what this questions about, but if you know how and want to drop it here, that'd be cool.
There are a few different ways you could go about this, but the basic idea is to know how many rows you printed, and if it's less than 12, print empty rows until you have the 12 you need. Here's one example:
Assuming you have your query results in an array called $data:
<table>
<?php
foreach ($data as $row) {
echo "<tr><td>{$row['col1']}</td><td>{$row['col2']}</td><td>{$row['col3']}</td></tr>";
}
if (count($data) < 12) {
for ($i=0; $i < 12-count($data); $i++) {
echo "<tr><td colspan='3'>EMPTY ROW</td></tr>";
}
}
?>
</table>
You can try using
table-layout: fixed;
Property in table style.
instead of the normal while($stmt->fetch()) use a for loop that iterates 12 times.
something like:
$dofetch = true;
for ($i = 0;$i<12;$i++) {
?><tr><?php
if ($dofetch && $stmt->fetch()) {
echo $stuff;
} else {
$dofetch = false;
echo '--';
}
?></tr><?php
}

Change class for last two rows in a while loop

I have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?
For example I have a list of results in a 2x2 matrix with border-bottom: 1px on each result but I would like to display the bottom two without the border?
If you can use css3, it´s easy (I´ll use a list for the example):
li:nth-last-child(-n+2)
selects the last two li's.
If you want to do it in php, you can count the number of results, add a counter in your loop and add a class to the last two items.
Yeah just do it like this:
$result = //execute your query
$num_rows = mysql_num_rows($result;
$num_rows_different = 2;
$loop_counter = 0;
while ($loop_counter < $num_rows) {
if ($loop_counter < $num_rows - $num_rows_different) {
// with border
} else {
// no border
}
$loop_counter++;
}
I wouldn't use the CSS3 method due to its poor support...
I like the CSS way, but you'll need to know the total number of items you're listing. Then you can use a simple condition to check for that.
$total_items = [count of items];
$cnt = 0;
while($fetch as $row) {
...
if(++$cnt > ($total_items - 2)) {
// list with no border
} else {
// list with border
}
}

PHP, MySQL Per row output

Been all over the place and spent 8 hours working loops and math...still cant get it...
I am writing a CP for a customer. The input form will allow them to add a package deal to their web page. Each package deal is stored in mysql in the following format
id header item1 item2 item3...item12 price savings
The output is a table with 'header' being the name of the package and each item being 1 of the items in the package stored in a row within the table, then the price and amount saved (all of this is input via a form and INSERT statement by the customer, that part works) stored rows as well.
Here is my PHP:
include 'dbconnect.php';
$query = "SELECT * FROM md ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//Print 4 tables with header, items, price, savings
//Go to next row (on main page) and print 4 more items
//Do this until all tables have been printed
}
mysql_free_result($result);
mysql_close($conn);
Right now the main page is simpley a header div, main div, content wrap and footer div.
Ideal HTML output of a 'package' table, not perfect and a little confusing
$header
$item1
$item2
ect...
$price$savings
I basically want the PHP to print this 4 times per row on the main page and then move to the next row and print 4 times and continue until there are no more items in the array. So it could be row 1 4 tables, row 2 4 tables, row 3 3 tables.
Long, confusing and frustrating. I about to just do 1 item per row..please help
Jake
You say "tables", but do you mean cells?
The basic flow would be:
$res = mysql_query(...) or die(mysql_error());
if (mysql_numrows($res) == 0) {
... say there's nothing to show ...
} else {
... print table header ...
while($row = mysql_fetch_assoc($res)) {
... print row ...
}
... print table footer
}
if i get your question right you need to use a loop, something like a for
while ($row = mysql_fetch_array($result)) {
for($i=1; $i<=3; $i++){
//print table (change $i values to change number of loops)
}
}
if i didnt get it right, please post an example of how the table should look like.
$items_per_line=4;
$counter=$items_per_line;
while ($row = mysql_fetch_array($result)) {
if($counter <1){
$counter=$items_per_line;
// goto next pages
}
// print header etc.
$counter--;
}

Split records into two columns

I have a "student" table, having around 5,000 records, in my DB. I want to display those records in two divs. How do I do that without executing the query twice; only using a single query?
display example http://www.freeimagehosting.net/uploads/f1c6bb41eb.gif
Just use CSS3. Not sure how widely it is supported but saves a lot of headache and is a lot more powerful when making changes.
Use column-count, and column-width to control the number of columns and width of each column. Here's some sample code and some pretty impressive results. Prefix -webkit and -moz for now until its standardized across all browsers.
.multi-column {
/* Standard */
column-count: 2;
column-width: 150px;
/* Webkit-based */
-webkit-column-count: 2;
-webkit-column-width: 150px;
/* Gecko-based */
-moz-column-count: 2;
-moz-column-width: 150px;
}
Applied to this <div>
<div class="multi-column">
Ethelred of Wessex
Louis XII of France
George Frideric Handel
George Washington
Charles Deslandes
Andrew Jackson
Alfred Vail
William McKinley
Woodrow Wilson
Abdul-Aziz ibn Saud
Fidel Castro
Charles de Gaulle
Leonardo da Vinci
</div>
Don't you wanna see how it looks like after all this hard work?
But what if there were 3 columns? No problem.
But there's no way it can handle 4 columns you'd say:
Enough! I gotta stop adding these now
God please make it STOP!!
Just find where the "middle" is and output the end tag of the div tag and the start tag of the second div:
<?
$rowcount = mysql_num_rows($recordset);
echo "<div id='div1'>";
$i = 0;
while ($d = mysql_fetch_object($recordset)) {
echo $d->somefield;
$i++;
if ($i == floor($rowcount / 2)) {
//we have reached the mid-point, let's close the first DIV
echo "</div><div id='div2'>";
}
}
echo "</div>";
?>
get_column() function could help, it will calculate column for each item you want to show.
this sample script show how to print in two columns, but you can change it in two minutes to fix your needs if you need other number of columns.
<?php
// sample query, get members
$query = mysql_query("select name from persons");
// count total number of items to show
$total = mysql_num_rows($query);
// initiate row counter
$counter = 1;
// initiate columns contents
$column_1 = '';
$column_2 = '';
while($row = mysql_fetch_assoc($query)){
// caluculate column for current element from total items to be showed number of columns and current item
$column = get_column($total, 2, $counter);
if($column == 1){
$column_1 .= $row['name'].'<br>';
}
if($column == 2){
$column_2 .= $row['name'].'<br>';
}
$counter++;
}
// show content in two table comments
echo "<table>
<tr>
<td>$column_1</td>
<td>$column_2</td>
</tr>
</table>";
?>
and the function is:
<?php
/**
* Calculate column number where an item should be displayed on a "newspaper style"
* or "phoneguide style" report according its postion
* used to put same number of items on each column
*
* receive 3 numbers: $vp_total_size: total number of items on report
* $vp_columns : number of columns of report
* $vp_element : element position for item (1 to $vp_total_size)
*
* by Marcos A. Botta <marcos DOT botta AT gmail DOT com>
* 02/02/2007
*
*/
function get_column($vp_total_size, $vp_columns, $vp_element){
if($vp_element <= 0){
return 1;
}
if($vp_element < $vp_columns &&
$vp_columns >= $vp_total_size){
return $vp_element;
}
$vl_avg_items_by_column = $vp_total_size / $vp_columns;
$vl_items_on_first_columns = ceil($vl_avg_items_by_column);
$vl_items_on_last_columns = floor($vl_avg_items_by_column);
$vl_column_limit = ($vl_avg_items_by_column - $vl_items_on_last_columns) * $vp_columns;
$vl_allocated_items = 0;
for($i=1;$i<$vp_columns;$i++){
if($i < $vl_column_limit ||
"$i" == "$vl_column_limit"){
$vl_items_on_current_column = $vl_items_on_first_columns;
}
else{
$vl_items_on_current_column = $vl_items_on_last_columns;
}
$vl_allocated_items += $vl_items_on_current_column;
if($vp_element <= $vl_allocated_items){
return $i;
}
}
return $vp_columns;
} // get_column()
?>
good luck!
My implementation:
<?php
$students = array(1,2,3,4,5);
$split = floor(count($students)/2);
echo '<div id="parent"><div id="col-1">';
$i = 0;
foreach($students as $student)
{
echo 'Student #' . $student . '<br />';
if($i == $split)
{
echo '</div><div id="col-2">';
}
$i++;
}
echo '</div></div>';
Using the CSS3 Webkit/Moz only features are in my opinion very bad practice.
Why dont you try this code, its simple using only css, easy to understand, working in ie and mozilla...
<style type="text/css">
.ulcol
{
float: left;
width: 400px;
margin: 0;
padding: 0;
list-style: none;
}
.licol
{
float: left;
width: 200px; /*half width of the ulcol width*/
margin: 0;
padding: 0;
}
</style>
<?php
$query = mysql_query("select * from table_name") or die("Error Occured,check again");
echo '<ul class="ulcol">';
while($row = mysql_fetch_assoc($query))
{
$vartitle = $row[db_row_title];
echo '<li class="licol">';
echo $vartitle
echo '</li>';
}
echo '</ul>';
?>
Maybe split the array into two then implode them and then print both halves on each div.
I prefer to minimize any early use of "echo", because tomorrow you will want to move this in a function or a method, where "echo" should be avoided. Moreover, with the "echo" in the loop you've lost the array structure inherent to databases, and you need this structure to manipulate your data. So I would rather fill an array, process it, then implode to output.
And I would use styled bullet points to display the items, because you apparently want to display a list of items. In pseudo php code:
while row = fetch(sql)
lines[] = "<li>row_data</li>"
end
// work on the lines array, eg insert "</ul><ul>" in the middle
echo "<ul>".implode("\n",lines)."</ul>"
Try something like this
// connection goes there
$q = "SELECT `name` FROM students";
$result = mysql_query($q);
$students = array();
while($row=mysql_fetch_assoc($result)) {
$students[] = $row['name'];
}
$students_count = sizeof($students);
// chunkes into a two parts , want more columns ? just change "2" to other number
$students_chuncked = array_chunk($students,ceil($students_count/2),true);
//now display
foreach ($students_chuncked as $student_div_data){
echo '<div>',explode($student_div_data,'<br/>'),'</div>';
}

PHP MYSQL - Explode help

Greetings,
I have data stored on mysql with delimiter "," in 1 table.
I have rows and column stored on database too.
Now i have to output the data using rows and column number stored on database to draw the table.
Rows and column number are user input, so it may varies.
Let say, there is number 3 on column and 3 on rows.
I need to do it like display like,
|___d1__|___d2__|___d3__|
|___d4__|___d5__|___d6__|
|___d7__|___d8__|___d9__|
Where d1-d9 would be the data stored on mysql database with delimiter "," in one table.
Thanks for helping me.
You can turn the comma separated values from your data column into an array using the explode() function:
<?php
$result = mysql_query('SELECT rows, columns, data from table_name where id=1');
$record = mysql_fetch_assoc($result);
$rows = $record['rows'];
$columns = $record['columns'];
$data = explode(',' , $record['data']);
if (sizeof($data) != $rows * $columns) die('invalid data');
?>
To display the table, you need two nested for-loops:
<table>
<?php for ($row = 0; $row < $rows; $row++) : ?>
<tr>
<?php for ($column = 0; $column < $columns; $column++) : ?>
<td>
<?php echo $data[$row * $columns + $column]; ?>
</td>
<?php endfor ?>
</tr>
<?php endfor ?>
</table>
This won't help you solve this very problem, but a word of good advice: never EVER write comma seperated values into a database field. You can't sensibly query information stored like this, and your application code will be cluttered with ugly conversions. Instead, use a seperate table with a reference to the main table and one row per value.
assuming that user set table size for 2 rows and 3 columns and makes some input fot 6 cells, data which will go to database will be
2,3,d1,d2,d3,d4,d5,d6
when you will fetch data from cell and make explode on fetched string you will get 1 dimension array with 8 elements
$r = $e[0] rows
$c = $e[1] cols
$e[2-7] data
wrtite openning < table > tag
two loops, one in another,
first one will generate code for start of row
wrtite openning < tr > tag
inside one will genereate code for row.
write opening < td > tag
write data $e[1 + position calulated from inside and outside loops]
write closing < td > tag
end of inside loop
wrtite closing < tr > tag
end of outside loop
wrtite closing < table > tag
It should give you the idea

Categories