在获取行之间添加
Add in between fetch rows
我想从我的 mysql 中获取 4 行并在每行后添加不同的文本
$rel=mysql_query("SELECT * FROM b_topics WHERE MATCH (subject) AGAINST('$title') LIMIT 4");
if(mysql_num_rows($rel)<0) {
echo ""
}
else {
echo" <br><strong><div align='center'>Related Topics</div <br>";
while($rel2=mysql_fetch_assoc($rel)) {
$gnum=mysql_num_rows($rel2);
if($gnum==1) {
echo" yes"
}
if($gnum==2) {
echo" no yes"
}
if($gnum==3) {
echo"yes yes"
}
if($gnum==4) {
echo" wmjayes";
}
$reltitle=$rel2["subject"];
$relid=$rel2["id"];
echo" <a href='showtopic.php?id= $relid'>$reltitle>$gnum</a><br>";
}
}
由于 mysql_fetch_assoc 只包含一行,因此计算行数对您不起作用。此外,mysql_num_rows 告诉您查询结果中返回了多少行($rel),它不会告诉您您在哪一行。
改为考虑使用计数器变量:
$rel=mysql_query("SELECT * FROM b_topics WHERE MATCH (subject) AGAINST('$title') LIMIT 4");
if(mysql_num_rows($rel)<0) {
echo ""
}
else {
$counter = 0;
echo "<div style='text-align: center; font-weight: bold; margin: 10px'>Related Topics</div>";
while($rel2=mysql_fetch_assoc($rel)) {
$counter++;
if($counter==1)
echo" yes";
elseif($counter==2)
echo "no yes";
elseif($counter==3)
echo "yes yes";
elseif($counter==4)
echo" wmjayes";
$reltitle=$rel2["subject"];
$relid=$rel2["id"];
echo" <a href='showtopic.php?id= $relid'>$reltitle>$counter</a><br>";
}
}
此外,为了让您的代码更快一点,请考虑使用 elseif
或 else if
而不是多个 if
语句。您可能还想查看 PHP switch
语句以寻找替代方案。
还有两件事你不应该做:
1) 不要使用mysql函数,使用mysqli或PDO函数。 mysql PHP 中的函数已弃用,不应再使用。
2) 不要用<br>
加间距。此外,块级元素(例如 div)不能出现在行内元素(例如 strong)中。对于这两个,请改用 CSS。我已经为您修改了它以使用内联 CSS 但您最终应该将它放在外部 CSS 文件中。
我想从我的 mysql 中获取 4 行并在每行后添加不同的文本
$rel=mysql_query("SELECT * FROM b_topics WHERE MATCH (subject) AGAINST('$title') LIMIT 4");
if(mysql_num_rows($rel)<0) {
echo ""
}
else {
echo" <br><strong><div align='center'>Related Topics</div <br>";
while($rel2=mysql_fetch_assoc($rel)) {
$gnum=mysql_num_rows($rel2);
if($gnum==1) {
echo" yes"
}
if($gnum==2) {
echo" no yes"
}
if($gnum==3) {
echo"yes yes"
}
if($gnum==4) {
echo" wmjayes";
}
$reltitle=$rel2["subject"];
$relid=$rel2["id"];
echo" <a href='showtopic.php?id= $relid'>$reltitle>$gnum</a><br>";
}
}
由于 mysql_fetch_assoc 只包含一行,因此计算行数对您不起作用。此外,mysql_num_rows 告诉您查询结果中返回了多少行($rel),它不会告诉您您在哪一行。
改为考虑使用计数器变量:
$rel=mysql_query("SELECT * FROM b_topics WHERE MATCH (subject) AGAINST('$title') LIMIT 4");
if(mysql_num_rows($rel)<0) {
echo ""
}
else {
$counter = 0;
echo "<div style='text-align: center; font-weight: bold; margin: 10px'>Related Topics</div>";
while($rel2=mysql_fetch_assoc($rel)) {
$counter++;
if($counter==1)
echo" yes";
elseif($counter==2)
echo "no yes";
elseif($counter==3)
echo "yes yes";
elseif($counter==4)
echo" wmjayes";
$reltitle=$rel2["subject"];
$relid=$rel2["id"];
echo" <a href='showtopic.php?id= $relid'>$reltitle>$counter</a><br>";
}
}
此外,为了让您的代码更快一点,请考虑使用 elseif
或 else if
而不是多个 if
语句。您可能还想查看 PHP switch
语句以寻找替代方案。
还有两件事你不应该做:
1) 不要使用mysql函数,使用mysqli或PDO函数。 mysql PHP 中的函数已弃用,不应再使用。
2) 不要用<br>
加间距。此外,块级元素(例如 div)不能出现在行内元素(例如 strong)中。对于这两个,请改用 CSS。我已经为您修改了它以使用内联 CSS 但您最终应该将它放在外部 CSS 文件中。