如何使用数据库中的值创建 PHP 两列表? [英] How to create PHP two column table with values from the database?

查看:34
本文介绍了如何使用数据库中的值创建 PHP 两列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含两列名称的表,其中名称取自数据库,但我不知道如何..我需要帮助.

姓名:詹姆斯、约翰、保罗、彼得

这是我的代码:

";$count = 0;$sql = "SELECT * FROM tbl_names";$q = mysql_query($sql);while($res = mysql_fetch_array($q)){$count++;echo "";for($i=1;$i<=2;$i++){echo "<td>{$res['id']}{$res['title']}</td>";}回声</tr>";}echo "</table>";?>

我希望输出是这样的:

+-------+-------+|詹姆斯 |约翰 |+-------+-------+|保罗 |彼得 |+-------+-------+

但我的代码返回:

+-------+-------+|詹姆斯 |詹姆斯 |+-------+-------+|约翰 |约翰 |+-------+-------+|保罗 |保罗 |+-------+-------+|彼得 |彼得 |+-------+-------+

我需要你的帮助.

解决方案

好吧,如果没有关系并且表格仅用于布局:

echo '

';while($res = mysql_fetch_array($q)){echo '

'.$res['id'] .$res['title'] .'</div>';}回声'</div>';

在 css 中:

.container { 宽度:400px;向左飘浮;}.container .item { 宽度:50%;向左飘浮;高度:一些固定高度;}//或 200 像素

无论如何,我更喜欢只使用表格来显示实际表格并避免将它们用于布局.你可以用 div 做任何你想做的事情(或者在这种情况下你也可以使用 ul 和 li.当然这不是必须的,但通常它需要较少的 HTML,对于 SEO 来说,html 内容比率是需要考虑的.如果你不这样做"如果你想要固定的高度,你可以像上面的 td/tr 示例一样包裹每一行.

I want to create a table of names with two columns where names are taken from the database but I don't know how.. I need help.

Names: James, John, Paul, Peter

Here's my code:

<?php
$con = mysql_connect("localhost","root","");
if(!$con){
echo "Unable to connect DB";
}else{
    $db = mysql_select_db("persons",$con);
    echo "Connected";
}
echo "<table border='1'>";
$count = 0;
$sql = "SELECT * FROM tbl_names";
$q = mysql_query($sql);
while($res = mysql_fetch_array($q)){
$count++;
    echo "<tr>";
        for($i=1;$i<=2;$i++){
                echo "<td>{$res['id']}{$res['title']}</td>";
        }
    echo "</tr>";   
}
echo "</table>";
?>

I want the output to be like this:

+-------+-------+
| James | John  |
+-------+-------+
| Paul  | Peter |
+-------+-------+

But my code return:

+-------+-------+
| James | Jame  |
+-------+-------+
| John  | John  |
+-------+-------+
| Paul  | Paul  |
+-------+-------+
| Peter | Peter |
+-------+-------+

I need your help.

解决方案

well, if there's no relation and the table is used only for layout:

echo '<div class="container">';
while($res = mysql_fetch_array($q)){
    echo '<div class="item">'.  $res['id'] . $res['title'] . '</div>';
}
echo '</div>';

and in css:

.container { width: 400px; float: left; }
.container .item { width: 50%; float: left; height: someFixedHeight; }
// or 200px

anyways, it's my preference to use tables only for displaying actual tables and avoid using them for layout. you can do anything you want with div's (or in this case you can also use ul and li. Of course it's not a must but normally it requires less HTML and for SEO the html-content ratio is something to consider. if you don't want fixed heights you can wrap each row as with the td/tr examples above.

这篇关于如何使用数据库中的值创建 PHP 两列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆