PHP + MySQL 用户自定义函数

我正在尝试使用我自己定义的 PHP 函数打印所有子类别项目。该函数的目的是打印所有父值为 的项目$parent。

这个函数有问题,为什么它没有按照我的意愿显示信息。为了让您理解我的目标,假设我们将项目分类在不同的组中,每个项目都有自己的组 ID。调用此函数我希望通过将组 ID 作为参数来获取同一组的所有项目$parent。

请有人帮我找出这个功能不起作用的原因。非常感谢。


<?php

include ('connect.php');

include ('head.html');


echo '<div class="categ"><p class="b">Health</p>';

function retrieve_column($parent){

    $sql = "SELECT item FROM category WHERE parent = $parent ORDER BY item ASC";

    $r = mysqli_query($dbc, $sql);

        if (!$r) {

            echo "Couldn’t make a connection to DB.";

        } else {

            while($row = mysqli_fetch_assoc($r)){

                for ($i=0; $i < mysqli_num_rows($r); $i++) {

                    echo '<a class="text" href="">' . $row['item'][$i] . '</a><br />';

                }

            }

        }

    }


$par = 1;

retrieve_column($par);

mysqli_free_r($r);

mysqli_close($dbc);

?>


慕桂英3389331
浏览 81回答 1
1回答

繁华开满天机

你这里有一个功能,你不能$dbc在本地使用。将此变量传递给函数:retrieve_column($par, $dbc);查询有一个小错误。$parent变量需要单引号:SELECT item FROM category WHERE parent = '$parent' ORDER BY item ASC对于循环,一个while ($row = mysqli_fetch_assoc($r))就够了<?phpinclude ('connect.php');include ('head.html');echo '<div class="categ"><p class="b">Health</p>';function retrieve_column($parent, $dbc){&nbsp; &nbsp; $sql = "SELECT item FROM category WHERE parent = '$parent' ORDER BY item ASC";&nbsp; &nbsp; $r = mysqli_query($dbc, $sql);&nbsp; &nbsp; &nbsp; &nbsp; if (!$r) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "Couldn’t make a connection to DB.";&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ($row = mysqli_fetch_assoc($r)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<a class="text" href="">' . $row['item'] . '</a><br />';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }$par = 1;retrieve_column($par, $dbc);mysqli_free_r($r);mysqli_close($dbc);?>
打开App,查看更多内容
随时随地看视频慕课网APP