New row if a number of cells have been reached
I'm trying to make a table of iframes (2 per row) and I query everything, but whenever it prints, everything is on a row of it's own even though I only tell every second one to. I can't figure out why this is happening:
<div id="main" style="width:1000px;">
<?php
$query = "SELECT * FROM开发者_JS百科 scripts";
mysql_connect("localhost", "root", "");
mysql_select_db("scriptsearch");
$results = mysql_query($query);
$num = mysql_num_rows($results);
mysql_close();
?>
<table border="0">
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
else{
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php }if($i % 2 == 0) echo '</tr>';/*end the row*/ } ?>
</table>
</div>`
Edit: I've tried Krynble's solution, but no matter how I modify it, it still doesn't show up how I expect.
There's an error in your loop.
Try this:
<?php
for($i = 0; $i <= $num; $i++){
if($i % 2 == 0) //is this the second one? if so, make a new row
echo '<tr>';
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php if($i % 2 == 1) echo '</tr>';/*end the row*/ } ?>
<?php if($i % 2 == 1) //close last row in case we haven't done it yet.
echo '</tr>';?>
You should print the iframe unconditionally, not inside an else. Besides, the closing </tr>
should be printed when $i
is odd.
Other people have commented on the php/html part, let me focus on the query part:
Don't do this:
$query = "SELECT * FROM scripts"; (1) select all ?
mysql_connect("localhost", "root", ""); (3) don't connect as root!
mysql_select_db("scriptsearch");
$results = mysql_query($query); (4) no check for errors?
$num = mysql_num_rows($results); (2) when you only want 1 count?
Do this instead:
$query = "SELECT count(*) as rowcount FROM scripts";
mysql_connect("localhost", "user1", "password");
mysql_select_db("scriptsearch");
if ($results = mysql_query($query)) {
$row = mysql_fetch_row($results);
$num = $row['rowcount'];
} else { echo "error....." }
You don't have an opening <tr>
tag in your table. You need to have a table row before you can put data in it.
精彩评论