Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display info in columns

Status
Not open for further replies.

bar2ayunie

Programmer
Apr 20, 2009
17
NL
Hello, I have a php code to display a few things from my sql database. Right now, it's listed in rows:
item 1
item 2
item 3
and so on

But I want to list all of the info in rows AND two columns, like this:
item 1 item 2
item 3 item 4
and so on

I've looked endlessly on google to find codes that will get me to create another column and I did find a few, but I can't seem to get it inserted in the code that I have. I did already manage to have only images be displayed in two columns and as many rows as there are images to display, but I can't seem to add in more information. I keep getting errors.

Is there anybody who knows how to continue? I wil display on the code that works perfectly, which is my starting code and that is the code that needs to be edited in order to display the items in two columns and rows.

This is de code I currently have:

Code:
(connecting to sql data)

$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");

$q = "select * from graphics_textures order by id desc ";
$result= mysql_query($q, $connection) or die
("Could not execute query : $q." . mysql_error());

$rows_per_page=10; 
$total_records=mysql_num_rows($result);
$pages = ceil($total_records / $rows_per_page);
$screen = $_GET["screen"];
if (!isset($screen))
$screen=0;
$start = $screen * $rows_per_page;
$q .= "LIMIT $start, $rows_per_page";
$result= mysql_query($q, $connection) or die
("Could not execute query : $q." . mysql_error());

while ($row=mysql_fetch_array($result))
{
$id=$row["id"];
$date=$row["date"];
$title=$row["title"];
$artist=$row["artist"];
$thumb=$row["thumb"];
$preview=$row["preview"];
$download=$row["download"];
$pcounter=$row["pcounter"];
$dcounter=$row["dcounter"];
?>


<table cellspacing="0" width="480"><tr><td>

<br><br>

</td></tr><tr><td>

<img src="<?php echo "$thumb"; ?>" align="left">

<b>ID:</b> <?php echo "$id"; ?><br>
<b>Title:</b> <?php echo "$title"; ?><br>
<b>Artist:</b> <?php echo "$artist"; ?><br>
<b>Date:</b> <?php echo "$date"; ?><br>
<a href="../../Downloads/Textures.php?id=<?php echo "$id"; ?>">Download</a> 
- [<?php echo "$dcounter"; ?>] <br>
</td></tr></table>
</td></tr></table>


<?php
} #end of while
?>

<p align="center">

<?php
if ($screen > 0) 
$j = $screen - 1;
$url = "Textures.php?screen=$j"; // EDIT change 'layout.php' if your page is different
echo "<a href=\"$url\">Prev</a>"; // EDIT change word 'Prev' if desired differently


for ($i = 0; $i < $pages; $i++) {
$url = "Textures.php?screen=" . $i; // EDIT change 'layout.php' if your page is different
$j = $i + 1;
echo "  <a href=\"$url\">$j</a>  ";
}

if ($screen < $pages-1) {
$j = $screen + 1;
$url = "Textures.php?screen=$j"; // EDIT change 'layout.php' if your page is different
echo "<a href=\"$url\">Next</a>";  // EDIT change word 'Next' if desired differently
}

?>

Thank you very much!
 
Yes I already read that topic and I tried to use the script, but I must do something wrong since it either goes into errors or I'm missing info or it's mainly just showing one column... That's what I asked in that topic, so maybe somebody can help me to put that code (the one from your link) together with my codes.

I should've said specified that I did that in my original post. Sorry. But can you help me out?
 
To show you what I mean, I re-created the code I made before combining the code of your link and my code. I get an error that the last line of code (no matter what the last line is) is wrong. It says: Parse error: syntax error, unexpected $end. I can delete everything after the code, it all is wrong. If I delete some stuff in the middle of my code, he tells me that the query is empty...

Do you know what's wrong?


Here's the code:
Code:
$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$id = $_GET['id'];

$columns = 4;
$q="SELECT * from graphics_textures where id='$id'";

//perform the query
$result = mysql_query($sql) or die(mysql_error());

while ($row=mysql_fetch_array($result))
{
$id=$row["id"];
$date=$row["date"];
$title=$row["title"];
$artist=$row["artist"];
$thumb=$row["thumb"];
$preview=$row["preview"];
$download=$row["download"];
$pcounter=$row["pcounter"];
$dcounter=$row["dcounter"];

//prepare the css
$column_css = (100/$columns) - 1;
$css = <<<HTML
<style>
.contentHolder {width:85%; margin: 0 auto; text-align:center;}
.innerHolder {width: $column_css; margin-right: 1px; float:left;}
.clear {line-height: 0.5px; visibility: hidden; clear:both;}
}
</style>

HTML;
//prepare the output
$output = <<<HTML
<div id="contentHolder">

HTML;
//iterate the recordset
while ($row = mysql_fetch_assoc($result)){
    $output .= <<<HTML
    <div class="innerHolder">
        <div class="imageHolder">
            <img src="<?php echo "$thumb"; ?>" align="left">

<b>ID:</b> <?php echo "$id"; ?><br>
<b>Title:</b> <?php echo "$title"; ?><br>
<b>Artist:</b> <?php echo "$artist"; ?><br>
<b>Date:</b> <?php echo "$date"; ?><br>
<a href="../../Downloads/Textures.php?id=<?php echo "$id"; ?>">Download</a> 
- [<?php echo "$dcounter"; ?>] <br>

        <div class="captionHolder">
            
        </div>
</div>
    
HTML;
}

//finish the output
$output .= <<<HTML
    <div class="clear">&nbsp;</div><!--- clear the floats for box model issues --->
</div> <!--- finish the contentHolder div --->

HTML;
?>
 
Those sound good, but they seema a little overly-complicated. Why not use the modulus (%) operator? Here's what I usually do:

Code:
$maxcol = 4;
$count = 0;
echo "<table>";
$result = mysql_query("SELECT * FROM table");
while ($t = mysql_fetch_object($result)) {

     if ($count % $maxcol == 0) echo "<tr>";

     echo "<td>";
     echo "Record output";
     echo "</td>";
     $count++;
     if ($count % $maxcol == 0) echo "</tr>";

}
echo "</table>";
 
Thx for helping out! From what you provided, I created the following code to insert the things I want to have displayed from the table. I used the plain code before and that totally works. Now I probably have an error somewhere in my code when trying to show the info from the table.

Code:
$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$id = $_GET['id'];

$maxcol = 2;
$count = 0;
echo "<table>";
$result = mysql_query("SELECT * FROM graphics_textures order by id desc");
while ($t = mysql_fetch_object($result)) {

$id=$t["id"];
$date=$t["date"];
$title=$t["title"];
$artist=$t["artist"];
$thumb=$t["thumb"];
$preview=$t["preview"];
$download=$t["download"];
$pcounter=$t["pcounter"];
$dcounter=$t["dcounter"];

     if ($count % $maxcol == 0) echo "<tr>";

     echo "<td>"; ?>
	 <img src="<?php echo "$thumb"; ?>" align="left">
	 
	<b>ID:</b> <?php echo "$id"; ?><br>
	<b>Title:</b> <?php echo "$title"; ?><br>
	<b>Artist:</b> <?php echo "$artist"; ?><br>
	<b>Date:</b> <?php echo "$date"; ?><br>
	<a href="../../Downloads/Textures.php?id=<?php echo "$id"; ?>">Download</a> 
	- [<?php echo "$dcounter"; ?>] <br>

     <?php echo "</td>";
     $count++;
     if ($count % $maxcol == 0) echo "</tr>";

}
echo "</table>";

?>

This shows the rows and the columns, but it doesn't seem to get the id and thus it shows no info. Also, I get the following error: Cannot use object of type stdClass as array. It refers to my $id=$t["id"]; lines. I've tried a few things to edit it, but it keeps saying there's an error on that line, or the info from the table that it's referring to isn't displayed. Do you know what to do?
Thx again!
 
this thread seems to be spiralling off! do you want to use css or tables to create the columns? css is easier/cleaner.

the table method is here
Code:
<?php
$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$id = $_GET['id'];

$maxcol = 2;
echo "<table>";
$result = mysql_query("SELECT * FROM graphics_textures order by id desc");
while ($t = mysql_fetch_object($result)) {
	echo "<tr>"; //start the row
	$col = 0; //reset the column
	do {
		echo "<td>"; //start cell
		if ($t !== false){
			echo <<<HTML
<img src="{$t->thumb}" align="left">
<b>ID:</b>{$t->id}<br/>
<b>Title:</b>{$t->title}<br/>
<b>Artist:</b>{$t->artist}<br/>
<b>Date:</b>{$t->date}<br/>
<a href="../../Downloads/Textures.php?id={$t->id}>Download">Download</a> - [{$t->dcounter}]
HTML;
		} else {
			echo "&nbsp;";	
		}
		echo "</td>"; //end cell
		$col++;	//advance the column counter
		$t = mysql_fetch_object($result); //retrieve next row of recordset
	} while ($col < $maxcol);
	echo "</tr>";
}
echo "</table>";

?>

the css method is like this
Code:
<?php
$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$id = $_GET['id'];
$cols = 3;
$size = (100/$cols) - 2;
$result = mysql_query("SELECT * FROM graphics_textures order by id desc") or die (mysql_error());
if (mysql_num_rows($result) > 0){
	echo <<<CSS
<style>
html, body, div, img {padding:0px; margin:0px;}
.results { width: 80%; margin: 0 auto; clear:both; overflow:hidden; }
.cell {width: {$size}%; float:left; margin-right: 1%;}
}
</style>
<div class="results">	
CSS;
	while ($t = mysql_fetch_object($result)) {
		echo <<<HTML
<div class="cell">
<img src="{$t->thumb}" align="left">
<b>ID:</b>{$t->id}<br/>
<b>Title:</b>{$t->title}<br/>
<b>Artist:</b>{$t->artist}<br/>
<b>Date:</b>{$t->date}<br/>
<a href="../../Downloads/Textures.php?id={$t->id}>Download">Download</a> - [{$t->dcounter}]
</div>
HTML;
	} //end while
	echo "</div><!--close results div--!>";
} else {
	echo "no results";
}

?>
 
Thank you very very much!! I'm sorry for spiralling off the thread... It doesn't matter which one I use, as long as I've got a method that works...

I've tried out both of the codes, both work (for which I'm greatful), but both have a mistake. I'm not saying you made a mistake, but I think that something from your code is messing up with the rest of mine.

I've got 27 records in my sql table, so when viewing the page, I should see 14 rows and two columns. However, the tables method has only 9 rows and it shows the following records:
Item 27 - Item 26
Item 24 - Item 23
Item 21 - Item 20
and so on. It misses one record after every row. I've changed nothing from the original code you provided (except the font size, but the problem was there before).
Here is the page with the table code:
The CSS method is messing up with the rest of my code. I have a copyright line at the bottom and a menu on the right (which uses PHP include to display), but nothing appears underneath the code, except for the shoutbox.
This is the rest of the code that I have on the bottom:
Code:
<br>
<center>
Bar2aYunie © 2008 - 2009. Content and Design by Yunie.<br>
    Version 2 - Forever Together
</center>
<br>
</font>
</div>

<?php include ("../../Layout_Files/Blue/Menu_Right.txt"); ?>
Again, nothing from the original code was changed except for the font size, but the problem was there before. This is the page with the CSS code:
I don't mind which one you help me fix, pick the one that's easiest.

Thank you very much for helping out!!!
 
a different approach

Code:
<?php
$connection = mysql_connect("$hostname" , "$user" , "$pass") or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
$id = $_GET['id'];

$maxcol = 2;
$result = mysql_query("SELECT * FROM graphics_textures order by id desc") or die (mysql_error());
$count = mysql_num_rows($result);
$rows = ceil($count/$maxcol);
echo "<table>";



echo "<table>";
for ($row=0; $row < $rows; $row++){
	echo "<tr>";
	for ($col=0; $col < $maxcols; $col++){
		echo "<td>";
		$t = mysql_fetch_object($result);
		if ($t === false) {
			echo "&nbsp;";
		} else {
			echo <<<HTML
<img src="{$t->thumb}" align="left">
<b>ID:</b>{$t->id}<br/>
<b>Title:</b>{$t->title}<br/>
<b>Artist:</b>{$t->artist}<br/>
<b>Date:</b>{$t->date}<br/>
<a href="../../Downloads/Textures.php?id={$t->id}>Download">Download</a> - [{$t->dcounter}]
HTML;
		}
		echo "</td>";
	}
	echo "</tr>";
}
echo "</table>";


$size = (100/$maxcol) - 2;
$result = mysql_query("SELECT * FROM graphics_textures order by id desc") or die (mysql_error());
if (mysql_num_rows($result) > 0){
	echo <<<CSS
<style type="text/css">
.results { width: 80%; margin: 0 auto; overflow:hidden; }
.cell {width: {$size}%; float:left; margin-right: 1%;}
}
</style>
<div class="results">	
CSS;
	while ($t = mysql_fetch_object($result)) {
		echo <<<HTML
<div class="cell">
<img src="{$t->thumb}" align="left">
<b>ID:</b>{$t->id}<br/>
<b>Title:</b>{$t->title}<br/>
<b>Artist:</b>{$t->artist}<br/>
<b>Date:</b>{$t->date}<br/>
<a href="../../Downloads/Textures.php?id={$t->id}>Download">Download</a> - [{$t->dcounter}]
</div>
HTML;
	} //end while
	echo "</div><!--close results div--!>";
} else {
	echo "no results";
}

?>
 
Thx, but this still doesn't fix my right menu... the right menu (as I said above about the CSS method) is still missing... any idea how this is possible?
 
i provided you both the table version and the css version. they are both working php methods for outputting the structured data.

i do not see anything in the css method code that would halt your script. perhaps you should debug by adding the following to your code
Code:
error_reporting(E_ALL);
ini_set('display_errors', true);

and then footprint your code so you can see where the problem may lie.
 
When I add that code below the rest, it shows nothing. When I add it above the php code, it shows these errors:

Notice: Undefined index: id in /customers/bar2ayunie.com/bar2ayunie.com/httpd. on line 57

Notice: Undefined variable: maxcols in /customers/bar2ayunie.com/bar2ayunie.com/httpd. on line 70

Line 57 is: $id = $_GET['id'];
Line 70 is: for ($col=0; $col < $maxcols; $col++){

I think I know why... I have set up my pages using: <div style="position: absolute; left: 255px; top: 382px; width: 480px"> and I use it to define where all of my content should be. At the end of the php code, it stops all divs, isn't that why the rest of my code isn't showing?

If so, isn't it easier to fix the tables code? That one is perfect, it's only missing every third item... I dunno why, but I thought that maybe some small thing had to be changed in order to fix it.

I don't know what's wrong here... I am certain your codes are correct, I just think that it can't combine with what I've got there...

I am very greatful for your help. I hope you know what's wrong here and how to fix it.
 
i provided a fix for the table code.

the line 70 should refer to $maxcol and NOT $maxcols
line 57 errors because there is no $_GET['id'].
 
Omg! I fixed it! I thought the problem lied within the <div>'s somewhere. I've had that problem before (a <div> or </div> too much or too many( and the rest of the page was broken and not displayed. So I started deleting something out of the closing echo <div> tags from the code you provided... And eventually I deleted "<!--close results div--!>" and the problem was gone!!!

I have one last question though... Do you know how I can let the query show only 10 rows per page and than switch over to another page?
 
Do you know how I can let the query show only 10 rows per page and than switch over to another page?

yes. implement 'paging'. there is an FAQ in this forum and i have posted many paging solutions here over the years. post back if you have problems implementing one.
 
I have found various options to use the paging script and I've used the following script:

Code:
$records_per_page = 10;

//find out how many records are in the table
$count_query = "SELECT count(*) from graphics_textures";
$rh = mysql_query ($count_query);
list ($record_count) = mysql_fetch_array($rh);


//calculate the maximum "page" that can be displayed.
$max_pages = floor($record_count / $records_per_page);


//This logic takes care of reacting to input.
if (isset($_GET['page']))
{
    if ($_GET['page'] > 1)
    {
        if ($_GET['page'] > $max_pages)
        {
            $current_page = $max_pages;
        }
        else
        {
            $current_page = $_GET['page'];
        }
    }
    else
    {
        $current_page = 1;
    }
}
else
{
    $current_page = 1;
}

$limit_start = ($current_page - 1) * $records_per_page;


//query the database for the required records
$data_query = "SELECT * FROM words LIMIT " . $limit_start . ", " . $records_per_page;
$rh = mysql_query ($data_query);


print '<html><body><table width="100%" border="1">';


//output the required records
while ($word_data = mysql_fetch_array($rh))
{
    print '<tr>';
    print '<td align="center" width="50%">' . $word_data['pkID'] . '</td>';
    print '<td align="center" width="50%">' . $word_data['word'] . '</td>';
    print '</tr>';
}


//this is the logic for the "previous" link display
print '<tr><td width="50%" align="center">';
if ($current_page > 1)
{
    print '<a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page - 1) . '">previous</a>';
}
else
{
    print '&nbsp;';
}
print '</td>';


//this is the logic for the "next" link display
print '<td width="50%" align="center">';
if ($limit_start + $records_per_page < $record_count)
{
    print '<a href="' . $_SERVER['PHP_SELF'] . '?page=' . ($current_page + 1) . '">next</a>';
}
else
{
    print '&nbsp;';
}
print '</td></tr></table><body></html>';

But then I get this error: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource. Other options I found also use mysql_fetch_array and I get the same warning.

Do you have any idea how to fix it?
 
change this
Code:
$data_query = "SELECT * FROM words LIMIT " . $limit_start . ", " . $records_per_page;

to
Code:
$data_query = "SELECT * FROM words LIMIT $records_per_page OFFSET $limit_start ";

and are you sure that this query should refer to the table 'words'? the count query refers to graphics_textures.
 
Okay, the error is gone! Thx! And yes, I'm stupid, it indeed had to state graphics_textures...

Anyway, no errors or whatsoever and I do have a 'next' button there, all of the 27 items are on the first page and by clicking on the next button leads to the same page or at least with the same items. What must I change?
 
i don't see much wrong with your code (should use ceil() rather than floor() but this is not the reason). i suspect that something is going wrong in the query.

here is a version of your output into some paging code that i wrote a little while ago. i have not checked this to make sure it works, and i will leave you to style as you see fit.

Code:
<?php
$limit = 10;
$table = 'graphics_textures';
//get requested page
$page = empty($_GET['page']) ? 1 : (int) $_GET['page'];
//calculate offset
$offset = ($page - 1) * $limit;

//construct query
$query = "Select SQL_CALC_FOUND_ROWS * from $table LIMIT $limit OFFSET $offset";

//execute query
$result = mysql_query($query) or die (mysql_error());
$cResult = mysql_query("Select found_rows()") or die(mysql_error());
list($count) = mysql_fetch_array($cResult, MYSQL_NUM);

$pageNavBar = getPages($limit, $count, $page);
//start the output
echo <<<HTML
<style type="text/css">
/*make the page numbering smaller generally */
.pageNav{ font-size:smaller;}
.nav{ padding: 1px; margin: 1px;}
.prev{}
.last{}
.first{}
.next{}
.active {border-color:#fc160a;}
.select select {}
.page{ border: thin dotted #060409; background-color:#fdffeb;}
/*style links */
.page a {text-decoration:none; cursor:hand; color: #ad85ff;}
.page a:visited {text-decoration:none; cursor:hand; color: #ad85ff;}
</style>
<table width="100%" border="1">
<thead>
<tr>
	<td colspan="2">
		$pageNavBar
	</td>
</tr>
</thead>
<tfoot>
<tr>
	<td colspan="2">
		$pageNavBar
	</td>
</tr>
</tfoot>
<tbody>
HTML;
while ($row = mysql_fetch_assoc($result)){
	echo <<<HTML

<tr>
	<td align="center" width="50%">{$row['pk_id']}</td>
	<td align="center" width="50%">{$row['word']}</td>
</tr>
HTML;
}
echo '</tbody></table>';

function getPages($limit, $count, $page){
	//put the url into a variable
	$s = ltrim($_SERVER["SCRIPT_NAME"] ,'/');
	//calculate the number of pages needed
	$nPages = ceil($count/$limit);
	//do the first/last prev/next buttons
	$first = "<span class=\"first nav\"><a href=\"$s?page=1>>>></a></span>";
	$last = "<span class=\"last nav\"><a href=\"$s?page=$nPages><<<</a></span>";
	$prev = ($page > 1) ? "<span class=\"prev nav\"><a href=\"$s?page=" . $page - 1 ."><-</a></span>" : "&nbsp;";
	$next = ($page < $nPages) ? "<span class=\"prev nav\"><a href=\"$s?page=" . $page + 1 .">-></a></span>" : "&nbsp;";
	
	//now construct the pages
	//if more than 10 then use a select
	if ($nPages > 10){
		$output = <<<HTMLJS
<span class="nav select">
	<select name="page" onchange="window.location='{$s}?page=' + this.options[this.selectedIndex].value;">
HTMLJS;
	
		for ($p=1; $p <=$nPages; $p++){
			$output .= "<option value=\"$p\">$p</option>";
		}
		$output .= '</select></span>';
	} else {
		$output = '';
		for ($p=1; $p<=$nPages; $p++){
			$active = ($p == $page) ? ' active' : '';
			$output .= "<span class=\"navPage{$active}\">$p</span>";
		}
	}
	return '<div class="pageNav">' . $first . $prev . $output . $next . $last . '</div>';
}
 
It still shows all of the items from the database. I didn't do any customising yet, since I wanted it to work first. I tried setting the limit from 10 to 5 to see if it makes any difference, but nothing has changed. Maybe it helps if I show you the page I'm using it on?

Here's the link:
Also, if you try to click any of the numbers for the next pages, I get an error, it leads to " I get the first part, but the span things shouldn't be in the link right?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top