2016-02-24 41 views
1

我有以下工作代码查询外while循环,使用循环的内部,一点儿也不工作

$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 .="]"; 

(不要看的变数名称缺口,could'nt找到更好的翻译比缺口它的复杂;-))

问题解释说:

当我把$query = mysqli_query...

while循环(略低于$notchDetails = mysqli_query...)外,

只得到1分的结果,其余的在空:while ($rs = mysqli_fetch_assoc($query)) { //result// }

房颤据我所看到的,它应该与$查询工作在循环之上。但我不明白为什么它不是。

有人可以解释为什么这不起作用吗?

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

+0

我是否正确地创建了JSON结构? –

+0

没错。我需要将多个JSON放入1个文本文档(使用序列化,然后对其进行加密)。你有更好的解决方案吗? –

+0

是的。 json_encode() –

回答

1

mysqli_fetch_assoc正在迭代通过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)); 

您将有这里没有查询表结构的相同结果。

+0

谢谢。很好的解释! –

+0

@RamonBakker。不用谢。我也希望这个答案不仅可以作为你的问题的答案,而且还可以作为准备好的语句的一个例子,它比直接将变量插入查询更安全。 –

+0

我知道SQL注入,我知道如何防止它。 –