gpt4 book ai didi

php - 当使用 PHP 和 MySQL 循环其余代码时,如何仅显示一段代码一次?

转载 作者:行者123 更新时间:2023-11-29 06:23:26 25 4
gpt4 key购买 nike

我试图仅显示以下代码一次,而其余代码循环抛出。我的代码应该是什么样子以及应该放在哪里。截至目前,底部代码将不会显示,但如果我将其放入循环中,它将显示多次(不是我想要的)。

    //Display only once.
if (!empty($row['category']) && !empty($row['url'])){
echo '<h2>List of Links</h2>';
}

这是完整的代码。

// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT users.*, categories.*, users_categories.* FROM users_categories INNER JOIN users ON users_categories.user_id = users.user_id INNER JOIN categories ON users_categories.category_id = categories.id WHERE users_categories.user_id=3");

if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error($mysqli);
}
//Display only once.
if (!empty($row['category']) && !empty($row['url'])){
echo '<h2>List of Links</h2>';
}

$ctr = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if (!empty($row['category']) && !empty($row['url'])) {
if ($ctr%3 == 0) {
echo '<div>';
}
$ctr ++;
echo '<p"><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p>';
if ($ctr%3 == 0) {
echo '</div>';
}
}

}
if ($ctr%3 != 0) {
echo '</div>';
}

最佳答案

也许您正在寻找:

if (mysql_num_rows($dbc) > 0){
echo '<h2>List of Links</h2>';
}

通过将上面的代码替换为当前的 if 语句,标题将在查询返回行时显示,而不是在查询不返回任何内容时显示。

因此,完整的代码将是:

// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT users.*, categories.*, users_categories.* FROM users_categories INNER JOIN users ON users_categories.user_id = users.user_id INNER JOIN categories ON users_categories.category_id = categories.id WHERE users_categories.user_id=3");

if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error($mysqli);
}
//Display only once.
if (mysql_num_rows($dbc) > 0){
echo '<h2>List of Links</h2>';
}

$ctr = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if (!empty($row['category']) && !empty($row['url'])) {
if ($ctr%3 == 0) {
echo '<div>';
}
$ctr ++;
echo '<p"><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p>';
if ($ctr%3 == 0) {
echo '</div>';
}
}

}
if ($ctr%3 != 0) {
echo '</div>';
}

关于php - 当使用 PHP 和 MySQL 循环其余代码时,如何仅显示一段代码一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1690452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com