1. Trang chủ
  2. » Công Nghệ Thông Tin

PHP & MySQL Everyday Apps for Dummies phần 7 ppsx

45 273 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 45
Dung lượng 757,49 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

4 If the user has administrative permissions in this department, display links that allow the user to add or edit the content item.. case “details”: 1 Get the list of content details bas

Trang 1

<?php echo $elements_2[‘top’]?>

<! Beginning of Form 1 (right side) >

<form action=<?php echo $_SERVER[‘PHP_SELF’]?>

$type = $types_2[$field];

{ echo “<tr><td style=\”text-align: right;

echo “>$opt_name\n”;

} echo “</select>”;

} else { echo “<tr><td style=\”text-align: right; #101

<input type=”submit” name=”Button”

value=”<?php echo $elements_2[‘submit’]?>”>

</td></tr>

</table>

</form>

</td>

Trang 2

Following is a description of the numbered lines of code that appear in

double_form.inc, in Listing 7-3:

#27 Checks for the existence of an error message that is stored in the

$_GLOBALSarray If it is set, the error message is displayed

#36 For each element in the $fields_1array, which is used in the loginform, a form input element is constructed

#48 At line 48, the submit button is displayed This button, if clicked, willmake the form submit to Login.phpand the user’s user name andpassword will be evaluated

#63 The form created after line 63 is the registration form

#74 The issetfunction call checks for the existence of an error messagethat is stored in the $_GLOBALSarray If set, the error message is displayed

#82 The foreachstatement starts a loop through the elements that should

be displayed on the registration form, as defined by the $fields_2

array Line 84 looks up the HTML element type for the field in the

$types_2array (that is defined in fields_login.inc)

#85 This block of code creates the drop-down list of departments In a life CMS, you will probably find tighter security In the CMS example inthis chapter, the user is trusted to choose her department Remember,

real-a user real-associreal-ated with real-a certreal-ain depreal-artment hreal-as real-administrreal-ative rightsfor that department A real-life CMS should include another layer ofadministration where a “super-user” can grant or revoke administra-tive privileges

#101 In the HTML around line 101, a form input element is constructed.

The length of the element is defined in the $length_2 array(found

in fields_login.inc)

#111 At line 111, the submit button is displayed This button, if clicked, will

make the form submit to Login.php, and Login.phpwill process istration information If the validation succeeds the user will be for-warded on to the Intranet home page If there is an error found whilevalidating the registration information, the login page will be redis-played and the errors will be noted on the screen in red text

Trang 3

Writing CompanyHome.php,

a data retrieval file

CompanyHome.phpis responsible for setting up the data elements used by

company.inc, a file that will display the HTML interface CompanyHome.php

is structured as a switchstatement, with caseblocks for each browse level

The browse level reflects the level in the site hierarchy at which the user isbrowsing, starting at the home page and drilling down to the content detaillevel The browse level is passed in the URL The switchstatement tests thebrowse level and executes the appropriate caseblock The following is anoverview of the structure of the script:

switch (browse_level) case “home”:

1 Get the list of departments from the Department database table.

2 Use the list of departments to build left-hand links to the departments.

3 Use the list of departments to build the main body text of the Web page that will include the department description text.

3 Use the list of content types to build main body text of links to the content type pages for the selected department.

case “content”:

1 Get the list of content items based on the department and content type that the user has selected.

2 If no content items exist, display a message indicating this.

3 If content items exist, list the items in a table.

4 If the user has administrative permissions in this department, display links that allow the user to add or edit the content item.

case “details”:

1 Get the list of content details based on the department, content type, and content item that the user has selected.

2 If the user is an administrator, show a form that includes elements that allow the user to upload files.

3 Show any downloadable files in the left-hand section of the Web page.

Trang 4

Listing 7-4 contains the PHP code that sets up data elements that are going to

be used to display the Web pages

L ISTING 7-4: G ETTING THE D EPARTMENT AND C ONTENT D ATA FROM M Y SQL

<?php /* Program: CompanyHome.php

* Desc: Displays a Web page that has four levels:

* 1) the home page, 2) a department page, 3) a

* content list page, and 4) a detail page.

“title” => “The Company Intranet”,

“header” => “The Company Intranet”,

$sql = “SELECT name, dept_id, description

FROM Department ORDER BY name”;

$results = mysqli_query($cxn, $sql);

Trang 5

$body_links = “”;

while($row = mysqli_fetch_assoc($results)) #50 {

$link = “$base_url?dept_id=” $row[‘dept_id’]

“&browse_level=department”;

$page[“left_nav_links”][$link] = $row[‘name’];

$body_links = “<li><a href=\”” $link “\”>” $row[‘name’] “</a> - “ $row[‘description’];

}

$page[“left_nav_header”] = “Departments”; #59

$page[“top”] = “Welcome to our Intranet”;

$page[“body_text”] = “Welcome to our Intranet “ “where each department shares content with “ “the whole company You can update your “ “own departments content too with our simple “ “interface.<p>Vist the departments’ “

“home pages: $body_links”;

$results = mysqli_query($cxn, $sql);

$row = mysqli_fetch_assoc($results);

$dept_name = $row[‘name’];

$dept_desc= $row[‘description’];

$page[“left_nav”] = “$dept_name Content”;

$page[“body_text”] = “$dept_name - $dept_desc”;

$sql = “SELECT a.name, a.type_id,

count(b.content_id) FROM Content_Type a

LEFT OUTER JOIN Content b on a.type_id = b.content_type and b.dept_id = $dept_id GROUP BY a.name, a.type_id ORDER BY name”;

$results = mysqli_query($cxn, $sql);

$body_links = “”;

while($row = mysqli_fetch_assoc($results)) #92 {

Trang 6

and b.content_type = $type_id WHERE c.dept_id = $dept_id ORDER BY content_date DESC”;

if (!isset($area_name) && $type_id == $row[“type_id”]) {

Trang 7

$page[“col_headers”][“create_date”] = “Created On”;

$page[“col_headers”][“created_by”] = “Created By”;

$page[“top”] = “$dept_name - $area_name”;

$trail = “ - <a href=’$base_url?dept_id=$dept_id”

$sql = “SELECT a.name as dept_name, b.name

FROM Department a, Content_Type b WHERE b.type_id = $type_id

and a.dept_id = $dept_id ORDER BY name”;

$results = mysqli_query($cxn, $sql);

$body_links = “”;

$content_count = 0;

while($row = mysqli_fetch_assoc($results)) #198 {

$area_name = $row[“name”];

$dept_name = $row[“dept_name”];

continue;

Trang 8

$sql = “SELECT content_id, dept_id, content_date,

content_type as type_id, title, description, create_date, created_by, last_upd_date, last_upd_by FROM Content

WHERE content_id = $content_id”;

$results = mysqli_query($cxn, $sql);

if ($row = mysqli_fetch_assoc($results)) {

foreach ($row as $key => $value)

$$key = $value;

}

$sql = “SELECT download_id, file_name

FROM Content_Download WHERE content_id = $content_id”;

$results = mysqli_query($cxn, $sql);

while($row = mysqli_fetch_assoc($results)) #242 {

Trang 9

$page[“body_text”] = “<center><u>Add Downloads</u>”;

for ($i = 0; $i < 3; $i++) {

<input type=’reset’ name=’action’

value =’Reset Form’>

<input type=’submit’ name=’action’

value =’Cancel’>

<input type=’submit’ name=’action’

value =’Save Changes’>

</center>”;

$page[“top”] = “ Edit/Create”;

} else {

}

?>

Trang 10

Following is a description of the numbered lines of code that appear in

CompanyHome.php, shown in Listing 7-4:

#7 Lines 7 and 8 ensure that a session has been started The issetcall

at line 7 is used because Admin.php, which also has a session_startcall, uses this file in an include call Without the isset check forthe $_SESSIONvariable, a notice might be displayed, like this: “Notice:

A session had already been started — ignoring session_start().”This notice would display on your PHP page if the error_reporting

level (set in the php.inifile) includes the E_NOTICElevel

#12 Lines 12 to 19 set up some strings and arrays that will be used in

company.incto display the Web page You can change the title,header, and bottom variables to reflect the name of your company.The left_nav, body_links, col_headers, and data_rowselementsare actually lists of data elements

#24 Here a variable named $trailis defined This string will be used tobuild a trail of links that will represent the hierarchy of the site thatthe user has traversed In Figure 7-3 earlier in this chapter, you seethe trail includes Home, the department being browsed (HumanResources), and the content area being browsed (FAQ)

#27 Line 27 and 28 check that the user is registered and has logged in Youcan remove these lines if you want to open up the Web site to unregis-tered users Some intranet Web sites don’t require a login unless theuser is trying to enter an administrative part of the site

#32 Lines 30 to 34 set the $adminvariable to either TRUEor FALSE The

$adminvariable, defined at line 22, is used to determine whether auser has administrative privileges to the area of the Web site that theuser is browsing

#38 Lines 38 to 40 set up the browse_levelvariable (really an element inthe $pagearray) The browse level determines whether the user islooking at

 The company’s home page (browse_levelof “home”)

 A department’s home page (browse_levelof “department”)

 A content item list (browse_levelof “content”)

 The detailed view of a single content item (browse_levelof

Trang 11

#59 Lines 59 to 66 fill in some page-level variables The “home”

browse_levelrepresents the main home page (as seen in Figure 7-1)

At this level, the departments are listed The left_nav_header, top,and body_textelements of the $pagearray are set here To make theCMS more managed (and less programmer-dependant), you can havethe CMS get these strings from the database Of course, to make theCMS truly user-managed, you have to build an interface to changethese strings

#70 Lines 70 to 88 are used to build the department-level display asshown in Figure 7-2 (shown earlier) The SQL that ends at line 88 uses

an OUTER JOINclause to make sure that all the content types areretrieved from the Content_Typetable If a regular join (INNER JOIN)were used here, then if there were no content items in the Content

table for the department, no rows would get returned The OUTERJOINclause gets the content types (from the Content_Typetable)regardless of if no content items exist (in the Contenttable)

#92 Begins a loop through the list of content types At lines 94 to 96, thelink to the content list is constructed

#110 Begins a block of code that builds the content-level display, as shown

in Figure 7-3, earlier in the chapter

#132 Begins a loop through the list of content items When the execution is

at this point in the code, the program knows the department and tent type in which the user is browsing

con-#144 At line 144, a check for content_idis done If content_idisn’t set,the loop continues its next iteration The content_idvariable can

be null because of the LEFT OUTER JOINclause in the SQL The code constructs the left-hand links to the content types regardless

of whether there are items in the Contenttable Line 153 assigns the

data_rowselement of the $pagearray to the results of the query

#156 Line 156 checks the number of content items processed in the

previ-ous loop If there are no content items, a message is displayed so thatthe user doesn’t simply see a blank page

#161 Begins a block of code that will add an administrative “add” link if the

user is an administrator of the department being browsed

#176 Lines 176 and 177 set up some display items to let the user know that

the level of data being browsed is the content level Lines 178 to 181set up the trail of links that helps the user determine where in theWeb site hierarchy she is browsing

#185 Begins a block of code that builds the content detail-level display, as

shown in Figure 7-4 and Figure 7-5

#198 Begins a loop through the list of content items When the execution is

at this point in the code, the program knows the department, the tent type, and the exact content item to which the user has browsed

Trang 12

con-#203 At line 203 (like at line 144), a check for content_idis done If the

content_idvariable isn’t set, the loop continues its next iteration

#222 If the $content_idcontains a value, the code knows that the user isediting an existing content item If this $content_idvariable isempty, then the user is creating a new item

#242 Begins a block of code that builds the list of downloads for a content

item In Figure 7-5, shown earlier, you can see in the left area of theWeb page that one download is available

#249 Begins a block of code that will add an administrative “del” link if the

user is an administrator of the department being browsed The “del”link will allow the user to delete the specific download item

#257 Begins a loop through the $_GETarray and sets up variables based onsubmitted HTML form elements

#264 Begins a block of code used to build links for administrative actions.

Users who aren’t administrators in a department in which they arebrowsing won’t see any administrative links and will be restricted to

a read-only view of the data

#297 This is the end of the CompanyHome.phpscript At this point in theprogram’s execution, the data needed to construct the HTML hasbeen set up Now, the company.incfile is included to actually buildthe HTML display

Writing company.inc, the main HTML display file

The preceding code file, CompanyHome.php(shown in Listing 7-4), does most

of the work of determining where the user is in the hierarchy of the Web site,

if the user is an administrator, and what the title is of the Web page The nextcode file, company.inc— shown in Listing 7-5 — does the display work Itparses the data lists set up in CompanyHome.phpand builds the HTML

L ISTING 7-5: B UILDING THE H OME AND D EPARTMENT HTML D ISPLAY

<?php /* File: company.inc

* Desc: Contains the code for a Web page that displays

* company and department data.

*/

?>

<html>

Trang 13

<head><title><?php echo $page[‘title’]?></title></head>

<body style=”margin: 0”>

<h3 align=”center”><?php echo $page[‘top’] ?></h3>

<div style=”font-size: 70%; font-weight: bold”>

<?php echo $trail ?></div>

echo “<tr><td >”

“<a href=\”$link\”>$label<p><p></td></tr>\n”;

}

if (sizeof($page[“left_nav_links”]) == 0) echo “<i>no items yet</i>”;

width=’100%’bgcolor=’gray’>

Continued

Trang 14

echo “<th nowrap>&nbsp;</th>\n”;

echo “</tr>\n”;

{ echo “<tr bgcolor=white>\n”;

foreach ($page[“col_headers”] as $key => $display) {

if (ereg(“date”, $key))

$row[$key] = date(“m/d/y”, strtotime($row[$key])); echo “<td nowrap>”.$row[$key].”</th>\n”;

} echo “<th nowrap>[“;

{ echo “<a href=\”Admin.php?action=delete”

“&dept_id=$dept_id&type_id=$type_id&content_id=” $row[“content_id”] “\”>delete</a>\n”;

} echo “<a href=\”CompanyHome.php?”

“&dept_id=$dept_id&type_id=$type_id&content_id=” $row[“content_id”] Æ

“&browse_level=details&edit=false\”>”

“view</a>\n”;

{ echo “<a href=\”CompanyHome.php?”

“&dept_id=$dept_id&type_id=$type_id&content_id=” $row[“content_id”] Æ

“&browse_level=details&edit=true\”>”

“edit</a>\n”;

} echo “]</th></tr>\n”;

} echo “</table>\n”;

} echo $page[“body_text”];

Trang 15

Following is a description of the lines of numbered code that appear in

company.inc, shown in Listing 7-5:

#6 Line 6 ensures that the file that has the code for connecting to thedatabase in included once

#16 Begins an HTML row and the left column that contains either thedepartments (when the user is at the home page), the content types(when the user is at a department page), or the available downloads(when the user is viewing a content item’s details)

#27 Begins the loop of the links on the left If no links exist, a no itemsyetmessage is displayed

#50 If the user is looking at a specific content item, the HTML is built bythe included files

#55 If more than one content item is listed, an HTML table listing the tent items is constructed Lines 57 to 65 set up the beginning of theHTML table

con-#66 Begins the loop that builds a row in the HTML table for each contentitem

#76 If the user is an administrator, a link to delete the content item isadded to the display

#86 If the user is an administrator, a link to edit the content item is added

to the display

Writing the content detail code

The Web site is designed in such a way that the user will drill down to thedetails The home page and the department page don’t list the full details of asingle content item The content detail page has all the information related to

a single content item

Writing fields_content.inc, setting up fields for the detail page

This next file — fields_content, shown in Listing 7-6 — sets up the elements

to display on the content item form The $fieldsassociative array maps theform element IDs to display names Some form names are left blank becausethey are hidden

Trang 16

The $fieldsassociative array sets up the key to display mapping Thevalues of this associative array will be used in the labels on the HTML form.The $typesassociative array sets up the key to HTML type mapping Thevalues of this associative array determine the type of HTML element to use inthe HTML form The $lengtharray maps an element key to the length of theHTML text box to be used in the display.

Writing content_form.inc, the content item detail display code

This next file — content_form, shown in Listing 7-7 — works as a form forediting data for a content item and also as a read-only view of a content item

If the user is an administrator, the form is shown, but non-administrators seeonly a read-only view of the data

L ISTING 7-6: S ETTING U P E LEMENTS AND T YPES U SED TO B UILD D ISPLAY

<?php /* File: fields_content.inc

* Desc: Contains arrays with the field names and form

* elements for the content pages.

“content_date” => “$area_name Date”,

“create_date” => “Creation Date”,

“created_by” => “Created By”,

“last_upd_date” => “Last Updated”,

“last_upd_by” => “Last Updated By”

Trang 17

L ISTING 7-7: B UILDING THE C ONTENT D ETAIL HTML D ISPLAY

<?php /* File: content_form.inc

* Desc: Contains the display code for a content item.

<td colspan=’2’ style=\”font-weight: bold;

$$field = date(“m/d/Y”, time($$field));

if (isset($$field) && $$field != “”)

$$field = date(“m/d/Y”, time($$field));

case “text”:

echo “<tr><td valign=top nowrap

style=\”text-align: right;

Trang 18

Following is a description of the numbered lines that appear in content_form.inc, shown in Listing 7-7:

#10 Begins a block of code that, if message_2is set in the $_GLOBALS

array, displays the error text that is stored in the array element

#19 The $editvariable gets set to either TRUEor FALSE If the user is anadministrator and the user clicked the Edit link to get to the detailpage, $editis set to TRUEand the page shows up in the edit mode.Otherwise, $editis set to FALSEand the page appears in a read-onlyview

#21 Begins a loop through the form elements HTML is constructed based

on the attributes set in the $typesarray and whether the user canedit the content item

#28 Begins a switchstatement that looks at the type of the element andbuilds the HTML based on that type

}

?>

<input type=”hidden” name=”browse_level” value=”details”>

<tr><td colspan=”2” style=”text-align: center”>

<p style=”margin-top: 05in”>

</table>

Trang 19

Writing Admin.php, the data manipulation code

When writing code that is going to make changes to data, you can never betoo careful when validating that the user has proper access to modify data,that the data being submitted is valid, and that related data relationships arevalid In the CMS example in this chapter, some validation is done, but forsimplicity’s sake only a couple checks are in place Ideally, you should look atevery line of code and ask yourself whether someone could in any way mali-ciously (or accidentally) reach an invalid state in the code You can use thebuilt-in assertfunction while debugging your code to check any codeassumptions

The brains of the CMS reside in the Admin.phpfile Items are added, deleted,and modified in this code file The form built in the content_form.incfilewill post its form elements to Admin.php Admin.phphas to validate data,redirect the user to the next display, and save the data to the database

Here is the basic flow of the administrative PHP file (Admin.php), which isshown in its entirety in Listing 7-8:

Loop through the submitted form elements.

Examine the action that the user is performing:

switch (action) case “delete”:

1 Delete the content details from the Content table for the content item that the user is trying to delete.

2 Delete any download items from the Content_Download table that are associated with the content item that the user is deleting.

case “Save Changes”:

1 Organize and validate the form elements being submitted.

2 If the user is saving a new content item, insert a new row into the Content database table.

3 If the user is saving an existing content item, update a row in the Content database table.

4 Loop through the files that have been uploaded and add their details to the Content_Download table.

case “DeleteDownload”:

1 Delete from the Content_Download table a single item.

Trang 20

L ISTING 7-8: U PDATING THE D ATABASE AND S AVE U PLOADED F ILES

<?php /* File: Admin.php

* Desc: Perform any data manipulation tasks, like

* creating, editing, or deleting content items.

$content_date = date(“Y-m-d”, $content_date);

$last_upd_date = date(“Y-m-d”, time());

Trang 21

WHERE content_id = $content_id”;

}

{

$sql = “INSERT Content (dept_id, content_type,

title, description, content_date, create_date, created_by,

last_upd_date, last_upd_by) VALUES ($dept_id, $type_id, ‘$title’,

$sql = “INSERT Content_Download (content_id, file_name)

VALUES ($content_id, ‘$file_name’)”;

mysqli_query($cxn, $sql);

$file_id = mysqli_insert_id($cxn); #103

$dest_dir = “files”.DIRECTORY_SEPARATOR.$file_id;

$dest_file = $dest_dir.DIRECTORY_SEPARATOR.$file_name;

Trang 22

Following is a description of the numbered lines that appear in Admin.php,shown in Listing 7-8:

#9 Begins a loop through the form elements that have been submitted to

Admin.phpby using the POSTform method

#11 Begins a loop through the form elements that have been submitted to

Admin.phpby using the GETform method

L ISTING7-8: (Continued)

{ if(!mkdir($dest_dir, 0700, TRUE)) die (“Can’t archive attachments to $dest_dir”);

} } break;

$sql = “SELECT a.dept_id, a.content_type

FROM Content a, Content_Download b WHERE b.download_id=$download_id AND a.content_id = b.content_id”;

Ngày đăng: 12/08/2014, 21:21

TỪ KHÓA LIÊN QUAN