我在 $_GET 变量上使用 switch 语句来在我的页面上生成我想要的结果。
我一直在质疑在这种情况下运行查询的最佳方式,因为我根本不知道最佳实践或方法。所以我在下面有一些伪代码,我想知道最好的方法是什么。
这很可能是一种性能无关紧要的情况,但如果确实如此,我想确保我做对了。
if(isset($_GET['type'])){
$var = $_GET['type'];
//run the query now and select everything needed from the DB for either switch case.
//view implications that involve pulled data
switch($var){
case '1':
//Or do I run the query here, getting only what I need for this situation
//view implications that involve pulled data
break;
case '2':
//again run the query here, getting only what I need for this situation
//view implications that involve pulled data
break;
}
}
这两种情况都共享来自数据库的一两个相似数据,但每种情况的大部分内容仅在该情况下才需要。
努力做到最好并保持代码尽可能干净和高效的底线。
谢谢!
最佳答案
当然最好只查询与你相关的数据。捆绑数据库、通过网络传输更多数据然后在 PHP 中做更多工作以过滤掉您不感兴趣的数据是没有意义的。所以你当然不应该查询“一切”。
另一方面,可能也没有理由switch
。必须有一种重写查询的方法,以便您可以将变量的值注入(inject)其中,并且根据该值,它会在任何一种情况下返回您想要的数据。这当然也取决于您的数据库模式。
无论您决定做什么,请注意不要暴露自己 SQL injection .
关于PHP 在 switch 语句中查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8365497/