简体   繁体   English

Mysqli检索数据并显示它们-最好的方法

[英]Mysqli Retrieve data and display them - best way

Which one of the options below is better 以下哪个选项更好

Option 1: 选项1:

//control file:  
$smpt = $con->query("SELECT id,name FROM customers");
//fetch all resuts 
$results = array();
while ($row = $result->fetch_assoc()) {
  $results[] = $row;
}    
$smpt->close();
//Note: PHP version < 5.3.0 so I can't use just $results->fetch_all('MYSQLI_ASSOC');

//view file:
foreach($results as $key=>$value) {
//display results
}
unset($results);

Option 2: 选项2:

//control file:  
$smpt = $con->query("SELECT id,name FROM customers");
//fetch all resluts 

//view file:
while($row = $result->fetch_assoc()) {
//display results
}
$smpt->close();

I am trying to completely separate the logic from presentation... Current I am using option 2 because with option 1 the script go through 2 loops. 我正在尝试将逻辑与表示形式完全分开...当前,我正在使用选项2,因为使用选项1时,脚本会经历2个循环。 one to fetch data and the other to display them. 一个用于获取数据,另一个用于显示数据。 But which one is better to use? 但是,哪个更好用?

Thanks 谢谢

It's always best that views only deal with presentation concerns. 最好只将视图处理表示问题。

So between the two options you've mentioned, I'd choose option 1 so you don't have to close $smpt inside the view ($smpt has nothing to do with the presentation layer). 因此,在您提到的两个选项之间,我将选择选项1,这样您就不必在视图内关闭$ smpt($ smpt与表示层无关)。

Option 1 allows you to re-use the $data variable so you can display the results twice, but the cost of this is that you potentially have a large amount of data stored in a variable. 选项1允许您重复使用$data变量,以便可以两次显示结果,但是这样做的代价是,变量中可能存储了大量数据。 You can clear this by using unset($data) once you are 100% sure you've finished with it. 您可以在100%确定完成后使用unset($data)清除它。

Option 2 requires less loops (only one instead of two) and doesn't need a extra variable to store the data. 选项2需要较少的循环(仅一个循环,而不是两个),并且不需要额外的变量来存储数据。 The cost of this is that the while loop can only be used once. 这样做的代价是while循环只能使用一次。

In the grand scheme of things, the differences in speed will be so minimal the user won't notice them, however if there are 20+ instances of this in once script then it could have a noticeable affect. 在总体方案中,速度差异将非常小,用户不会注意到它们,但是,如果一次脚本中有20多个实例,则可能会产生明显的影响。

I would recommend Option 2 providing that you'd only need to use the while loop once. 我建议选择2,前提是您只需要使用一次while循环。 Also, you could benchmark your scripts to see how they perform against one another. 另外,您可以对脚本进行基准测试,以查看它们彼此之间的性能如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM