组织文件的最佳方法是什么?

时间:2012-06-30 00:00:14

标签: php mysqli

我正在学习......我已经阅读了http://www.w3schools.com上的教程,我查看了www.php.net上的手册,并对一切如何运作有了很好的理解。但是我对如何构建我的页面感到困惑。什么东西应该放在同一个页面上,什么应该有它自己的页面,只是被包含/需要?

我仍然需要阅读的一件事是参数化,所以不要打扰我......

这就是我所拥有的:

a.php这是用户在www.mydomain.com/a.php中输入时看到的页面

<html>
<body>

<?php require("b.php"); ?>
// this requires that the page gets b.php and puts it here

<p>Name: <?php echo $row['firstname']; ?></p>
<p>Last Name: <?php echo $row['lastname']; ?></p>

</body>
</html>

b.php此页面包含在a.php

<?php

require("../dbunamepword.php");
// this connects to my database

$query = ("SELECT * FROM contacts WHERE contacttype IN ('Buyer','Seller','Buyer / Seller','Investor') AND leadstatus = 'New' ORDER BY date DESC"); 
$result = $mysqli->query($query) or die ("Error: ".mysqli_error($mysqli));
while ($row = $result->fetch_array()) {
// this fetches the data I want from the table in my db while all cases match above

$firstname = $row ['firstname'];     
$lastname = $row['lastname'];
// these are the rows in the table I want to fetch 

echo "First Name: " . $firstname . " " .$lastname ."<br />";
// this is how I want the data presented

}
?>

以下是我的问题提前感谢您:

1)使用函数如何使我在构建这些页面时受益,或者它们对我没有好处?

2)我不能忽略b.php上的echo,只需调用a.php中的行,如下所示,并输入foreach语句?我实际测试了这个并且我一直收到意外的$ end错误,所以我不确定这不是一个好方法或者我做错了什么?

<html>
<body>

<?php require("b.php"); ?>
// this requires that the page gets b.php and puts it here

<p>Name: <?php echo $firstname; ?></p>
<p>Last Name: <?php echo $lastname; ?></p>

</body>
</html>

3)假设我添加了一些if / else语句,如下所示,我应该将它们放在b.php中,还是将它们放在自己的文件c.php中,然后在b.php中添加一个include?

if(isset($_GET['leadstatus']) && $_GET['leadstatus'] == "All")
{
$query = "SELECT * FROM contacts WHERE contacttype IN ('Buyer','Seller','Buyer / Seller','Investor') ORDER BY contacts.date DESC";  
}
elseif (in_array($_GET['leadstatus'], array('New', 'Hot', 'Warm', 'Cold', 'Rejected', 'Closed')))
{  
$status = $_GET['leadstatus'];   
$query = "SELECT * FROM contacts WHERE leadstatus = '".$status."' AND contacttype IN ('Buyer','Seller','Buyer / Seller','Investor') ORDER BY contacts.date DESC";
}

4)在$querySELECT * FROM contacts WHERE contacttype IN ('Buyer','Seller','Buyer / Seller','Investor')而不是在每个if / else语句中输入,或者说我需要添加另一个字段,如'Renter',我可以做类似的事吗:

$type = ('Buyer','Seller','Buyer / Seller','Investor')

$query = ("SELECT * FROM contacts WHERE contacttype = $type AND leadstatus = 'New' ORDER BY date DESC"); 


if (($_GET['date'] == 'today'))
{     
$$query = "SELECT * FROM contacts WHERE contacttype = $type AND date = DATE(NOW()) ORDER BY date DESC";
}

if (($_GET['date'] == 'thisweek'))
{     
$thisweek = date('Y-m-d', strtotime('last sunday'));
$query = "SELECT * FROM contacts WHERE contacttype = $type AND date BETWEEN '$thisweek' AND '$thisweek' + INTERVAL 7 DAY ORDER BY date DESC";
}

1 个答案:

答案 0 :(得分:2)

我建议您开始使用微框架来帮助您组织代码。我更喜欢的是Silex,因为它促进/鼓励良好的编程习惯/实践,随着项目的增长,您可以无缝地演变为Symfony的更全栈的世界。

您没有需要框架,但我相信他们可以帮助您学习组织任何代码库的最佳实践,即使您决定不在某些项目中使用它。