PHP编写的语句(递归函数),可以解决这个问题吗


PHP Prepared statement (recursive function), can you work around this?

我在网上找到了这个标准类别和子类别输出递归函数:

function print_categ_list_product_page($parent = 0) {
    global $mysqli;
    $qry = "SELECT * FROM ami_categories WHERE ct_parent = '$parent'";
    $sqlResult = $mysqli->query($qry);
    if ($sqlResult->num_rows > 0) {
        while ($row = $sqlResult->fetch_assoc()) {
            echo'<ul style="padding-right: 10px;">';
                echo'<li class="menu_list_1" ><a href="products/?ct=' . $row['ct_id'] . '">' . $row['ct_name'] . '</a>';
                print_categ_list_product_page($row['ct_id']);
                echo'</li>';
            echo'</ul>';
        }
    }
}

我决不是php的专业人员。所以最近我开始使用这个名为Prepared Statement的方法来调用query,因为这样可以避免SQL注入。一切都很好,只是我想不出任何递归的方法。

function print_categories_2_0($parent = 0) {
    global $mysqli;
    $stmt = $mysqli->prepare("SELECT ct_id, ct_name FROM ami_categories WHERE ct_parent = ?");
    $stmt->bind_param('s', $parent);
    $stmt->execute();
    $stmt->bind_result($id, $name);
    while(mysqli_stmt_fetch($stmt)){ //fetch rows
        echo'<ul style="padding-right: 10px;">';
            echo'<li class="menu_list_1" ><a href="products/?ct=' . $id . '">' . $name . '</a>';
            print_categories_2_0($id);
            echo'</li>';
        echo'</ul>';
    }
    $stmt->close();
}

这根本不会输出任何东西。经过一些研究,我发现不可能有递归的Prepared Statement函数,因为在准备new之前必须关闭连接。

所以我的问题是,有人能帮我想出另一种方法,用prepared语句输出这个类别/子类别列表,而不使用递归函数吗。我在想:是否可以在SQL语句中使用INNER JOIN来执行类似的操作?

谢谢!

首先,请不要使用global。第二,事先准备好的发言的真正力量在于不必一遍又一遍地准备发言。因此,应该将prepare()中的mysqli_stmt对象作为参数传递。这样你就可以一次准备,然后一遍又一遍地执行。您可能还想告诉它,您期望的是整数i,而不是字符串s

$stmt = $mysqli->prepare("SELECT ct_id, ct_name FROM ami_categories WHERE ct_parent = ?");
print_categories_2_0($stmt); // Start the initial call
function print_categories_2_0(mysqli_stmt $stmt, $parent = 0) {
    $stmt->reset();
    $stmt->bind_param('i', $parent);
    $stmt->execute();
    $stmt->bind_result($id, $name);
    $data = array();
    // pull all the records out of the statement
    while($stmt->fetch()) $data[] = array('id' => $id, 'name' => $name);
    foreach($data as $row) { //fetch rows
        echo'<ul style="padding-right: 10px;">';
            echo'<li class="menu_list_1" ><a href="products/?ct=' . $row['id'] . '">' . $data['name'] . '</a>';
            print_categories_2_0($stmt, $row['id']);
            echo'</li>';
        echo'</ul>';
    }
}