【发布时间】:2020-11-26 16:33:27
【问题描述】:
我正在努力使用递归函数,因为它似乎覆盖了 foreach 循环中的变量。有人可以帮我确定如何解决这个问题吗?我想要完成的是在 SQL 数据库中找到的文件夹树,其中父文件夹包含子和孙子。我要生孩子,但只有第一个孩子的孙子孙女。我相信它在某处覆盖了声明。
function locateFolders($folderId, $arrIn = array()) {
$con = $_SESSION["dbConnection"]->conStr;
array_push($arrIn, $folderId);
// Select all folders that have this id as the parent folder id
$statement = "SELECT * FROM folders WHERE parentid='$folderId'";
$result = mysqli_query($con, $statement) or die(mysqli_error($con));
if (mysqli_num_rows($result) > 0) {
while ($r = mysqli_fetch_assoc($result)) {
array_push($arrIn, $r["id"]);
$statement2 = "SELECT * FROM folders WHERE parentid='".$r["id"]."'";
$result2 = mysqli_query($con, $statement) or die(mysqli_error($con));
while ($row = mysqli_fetch_assoc($result2)) {
return locateFolders($row["id"], $arrIn);
}
}
}
$arrIn = array_unique($arrIn);
return $arrIn;
}
【问题讨论】:
-
警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDO 或MySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。 Escaping is not enough!
-
在代码中使用
die(mysqli_error($conn));是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die?