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

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

问题描述

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

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.

名称:James,John,Paul,Peter

Names: James, John, Paul, Peter

这是我的代码:

<?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>";
?>

我希望输出如下:

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

但我的代码返回:

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

我需要你的帮助。

推荐答案

好吧,如果没有关系,表只用于布局:

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>';

和css:

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

无论如何,我最喜欢使用表格来显示实际情况表格并避免使用它们进行布局。你可以用div做任何你想要的东西(或者在这种情况下你也可以使用ul和li。当然它不是必须的,但通常它需要更少的HTML和搜索引擎优化的HTML内容比率需要考虑。如果你不我想要固定的高度,你可以像上面的td / tr一样包装每一行。

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天全站免登陆