在while循环中查询,使用内部循环,确实无法正常工作

时间:2016-02-24 12:54:03

标签: php mysql mysqli while-loop

我有以下工作代码

$notchDetails = mysqli_query($conn, "SELECT * FROM notches WHERE projectid = ".$projectid." LIMIT ".$offset.", ".$limit."");
// i want $query here //
$outp3 = "[";
if (mysqli_num_rows($notchDetails) > 0) {
  while($notch = mysqli_fetch_assoc($notchDetails)) {

    $query = mysqli_query($conn, "DESCRIBE $table");

    $count = count($notch);
    $allnotches[] = $notch["notchid"]; // $allnotches is needed further in script //
    if ($outp3 != "[") {$outp3 .= ",";}

    $outp3 .= "{";

    $x = 1;
    while ($rs = mysqli_fetch_assoc($query)) {
        $field = $rs["Field"];
        $outp3 .= '"'.$field.'":"'.$notch[$field].'"';
        if ($x != $count) { $outp3 .= ","; } 
        $x++;
    }   

    $outp3 .= "}";
  }
}
$outp3 .="]";

(不要看看var名称缺口,不能找到比缺口更好的翻译。它很复杂;-))

问题解释:

当我放置$query = mysqli_query...

在while循环之外(在$notchDetails = mysqli_query...下面),

它只提供1个结果,其余的留空:while ($rs = mysqli_fetch_assoc($query)) { //result// }

我可以看到,它应该与循环上方的$查询一起使用。但我不明白为什么会这样。

有人可以解释一下为什么会这样做吗?

P.S。将其置于循环之外的原因是性能/速度

1 个答案:

答案 0 :(得分:1)

mysqli_result正在迭代$query = mysqli_query($conn, "DESCRIBE $table");。当您结束迭代时,您无法再次迭代它。您可以创建一个新查询并对其进行迭代。

因此,当您将while置于mysqli_fetch_assoc循环之外时,您不会创建一个新的迭代查询,因此,在第一次迭代完成后,$fields = []; $table_structure = mysqli_query($conn, "DESCRIBE `notches`"); while ($row = $table_structure->fetch_assoc()) { $fields[] = $row['Field']; } $notch_details = mysqli_prepare( $conn, 'SELECT * FROM `notches` WHERE `projectid` = ? LIMIT ?, ?' ); $notch_details->bind_param('iii', $projectid, $offset, $limit); $notch_details->execute(); $notch_details = $notch_details->get_result(); $result = []; while($notch = $notch_details->fetch_assoc()) { $values = []; foreach ($fields as $field) { $values[$field] = $notch[$field]; } $result[] = $values; } $result = json_encode($result); 没有返回任何内容,因为你没有新的查询,旧的查询已被迭代。

我会做类似的事情:

$fields

正如您所看到的,我已准备好$notch_details = mysqli_prepare( $conn, 'SELECT * FROM `notches` WHERE `projectid` = ? LIMIT ?, ?' ); $notch_details->bind_param('iii', $projectid, $offset, $limit); $notch_details->execute(); $notch_details = $notch_details->get_result(); $result = json_encode($notch_details->fetch_all(MYSQLI_ASSOC)); 一次列表,稍后我将其用作字段列表,无需一次又一次地查询表格描述。

编辑另外,当您查询数据库并将数据作为关联数组提取时,您不需要了解表字段,因为结果中已经有字段名称:

public static partial class LogicFactory
{
    /// <summary>A factory for ILogic instances</summary>
    [PexFactoryMethod(typeof(ILogic))]
    public static ILogic Create(string defaultUICulture, bool saveSuccessful)
    {
        return Mock.Of<ILogic>(
        x =>
        x.GetUICulture(It.IsAny<string>()) == defaultUICulture &&
        x.Save(It.IsAny<string>(), It.IsAny<string>()) == saveSuccessful);
    }
}

在不查询表结构的情况下,您将获得相同的结果。