我有一个表用户
user(id, username, email, profile_pic) // Id is primary key
现在我想在PHP代码中的每次迭代中一次获取两行结果,因为我需要从数据库中显示两行。 我想以下面的方式显示我的结果。
示例
user1 user2
user3 user4
user5 user6
任何帮助将不胜感激。
感谢。
答案 0 :(得分:1)
您不需要一次获取两行。您需要正确创建视图脚本。
$counter=0;
echo '<table><tr>';
while($row = $result->fetch()) {
$counter++;
echo '<td>'.$row['user'].'</td>';
if ($counter%2 == 0) {
echo '</tr><tr>';
}
}
if ($counter%2 == 1) {
echo '<td> </td>'
}
echo '</tr></table>'
答案 1 :(得分:1)
最简单的方法是将所有用户加载到PHP中的数组中,并使用以下伪代码和PHP:
假设您的用户数组具有从0到用户数量的索引。 您应在每个单元格中引用的值(x = 0行,y = 0-cols) CellValue(x + 1 + y)
祝你好运!答案 2 :(得分:1)
想法是将用户表加入到
本身并根据你的意愿去做
规则。所以这是代码。试试吧。
--- DATA ---
create table user(id int, username varchar(100), email varchar(100), profile_pic varchar(100));
insert into user
(id , username , email , profile_pic )
values
(10, 'user1', 'x1@x.com', '111');
insert into user
(id , username , email , profile_pic )
values
(20, 'user2', 'x2@x.com', '222');
insert into user
(id , username , email , profile_pic )
values
(30, 'user3', 'x3@x.com', '333');
insert into user
(id , username , email , profile_pic )
values
(40, 'user4', 'x4@x.com', '444');
insert into user
(id , username , email , profile_pic )
values
(50, 'user5', 'x5@x.com', '555');
insert into user
(id , username , email , profile_pic )
values
(60, 'user6', 'x6@x.com', '666');
insert into user
(id , username , email , profile_pic )
values
(70, 'user7', 'x7@x.com', '777');
--- QUERY 1 ---
SELECT v1.ID as id1, v1.email as email1, v2.ID as id2, v2.email as email2
FROM
(
SELECT
@i:=@i+1 AS num,
u.*
FROM
(SELECT u1.* FROM USER u1 ORDER BY u1.id ASC) u,
(SELECT @i:=0) AS tbl
ORDER BY num ASC
) v1
JOIN
(
SELECT
@j:=@j+1 AS num,
u.*
FROM
(SELECT u1.* FROM USER u1 ORDER BY u1.id ASC) u,
(SELECT @j:=0) AS tbl
ORDER BY num ASC
) v2 ON ( v1.num = v2.num - 1 AND mod(v1.num, 2) = 1);
如果你想获得最后一行(ID = 7的那一行),也可以这样做。
--- QUERY 2 ---
SELECT v1.ID as id1, v1.email as email1, v2.ID as id2, v2.email as email2
FROM
(SELECT v0.* FROM
(
SELECT
@i:=@i+1 AS num,
u.*
FROM
(SELECT u1.* FROM USER u1 ORDER BY u1.id ASC) u,
(SELECT @i:=0) AS tbl
ORDER BY num ASC
) v0 WHERE MOD(v0.num, 2) = 1
) v1
LEFT JOIN
(
SELECT
@j:=@j+1 AS num,
u.*
FROM
(SELECT u1.* FROM USER u1 ORDER BY u1.id ASC) u,
(SELECT @j:=0) AS tbl
ORDER BY num ASC
) v2 ON ( v1.num = v2.num - 1 );
答案 3 :(得分:1)
无需修改获取数据的方式。下面是一个明文,简短的解决方案,仅使用前端代码解决:
$rownum = 0;
while($row = $result->fetch()) {
$rownum++;
echo $row['username'] . ($rownum %2 == 0) ? "\n" : ' ');
}