您的位置:首页 > 编程语言 > PHP开发

Head First PHP&MySQL学习笔记(六)

2015-03-01 14:19 741 查看
九. 串与定制函数

1. 利用like,%增加搜索的灵活性;LIMIT控制一个SQL查询返回多少行以及哪些行

2. PHP explode()函数将一个串分解为一个子串数组;PHP implode()函数由子串构造一个串;

PHP str_replace()函数可以实现“查找-替换功能”;PHP substr()函数允许抽取一个串的一部分;

3. 通过预处理数据,可以删除我们不想要的字符,使数据更易于处理

4. 利用定制函数,可以按名组织一个PHP代码块,以便轻松地重用

5. 跟踪分页数据的常用变量:

$cur_page:用过$_GET从脚本URL得到当前页$cur_pages。如果未通过URL传递当前页,$cur_page则设置为第1页(1);

$results_per_page:这是每一页上的显示结果数,可以根据页面的外观来选择,另外要考虑页面采用这种布局时放多少个搜索结果才合适。LIMIT字句的第二个参数就由这个变量确定;

$skip:计算开始当前页面上的行为之前要跳过的行数$skip。这个变量会控制每一页的结果从哪里开始,并为LIMIT字句提供第一个参数;

$total:运行一个不带LIMIT获取所有行的查询,然后统计结果数并存储在$total中

$num_pages:用$total除以$results_per_page计算页数$num_pages;

所以对于给定的搜索,总共有$total个匹配行,不过一次显示一页,每页包含$results_per_page个匹配行。共有$num_pages页,当前页由$cur_page标识

6. 代码示例:

<!-- connectvars.php -->

<?php
// Define database connection constants
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'riskyjobs');
?>


<!-- search.php -->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Risky Jobs - Search</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<img src="riskyjobs_title.gif" alt="Risky Jobs" />
<img src="riskyjobs_fireman.jpg" alt="Risky Jobs" style="float:right" />
<h3>Risky Jobs - Search Results</h3>

<?php
// This function builds a search query from the search keywords and sort setting
function build_query($user_search, $sort) {
$search_query = "SELECT * FROM riskyjobs";

// Extract the search keywords into an array
$clean_search = str_replace(',', ' ', $user_search);
$search_words = explode(' ', $clean_search);
$final_search_words = array();
if (count($search_words) > 0) {
foreach ($search_words as $word) {
if (!empty($word)) {
$final_search_words[] = $word;
}
}
}

// Generate a WHERE clause using all of the search keywords
$where_list = array();
if (count($final_search_words) > 0) {
foreach($final_search_words as $word) {
$where_list[] = "description LIKE '%$word%'";
}
}
$where_clause = implode(' OR ', $where_list);

// Add the keyword WHERE clause to the search query
if (!empty($where_clause)) {
$search_query .= " WHERE $where_clause";
}

// Sort the search query using the sort setting
switch ($sort) {
// Ascending by job title
case 1:
$search_query .= " ORDER BY title";
break;
// Descending by job title
case 2:
$search_query .= " ORDER BY title DESC";
break;
// Ascending by state
case 3:
$search_query .= " ORDER BY state";
break;
// Descending by state
case 4:
$search_query .= " ORDER BY state DESC";
break;
// Ascending by date posted (oldest first)
case 5:
$search_query .= " ORDER BY date_posted";
break;
// Descending by date posted (newest first)
case 6:
$search_query .= " ORDER BY date_posted DESC";
break;
default:
// No sort setting provided, so don't sort the query
}

return $search_query;
}

// This function builds heading links based on the specified sort setting
function generate_sort_links($user_search, $sort) {
$sort_links = '';

switch ($sort) {
case 1:
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=2">Job Title</a></td><td>Description</td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=3">State</a></td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=5">Date Posted</a></td>';
break;
case 3:
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=1">Job Title</a></td><td>Description</td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=4">State</a></td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=3">Date Posted</a></td>';
break;
case 5:
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=1">Job Title</a></td><td>Description</td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=3">State</a></td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=6">Date Posted</a></td>';
break;
default:
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=1">Job Title</a></td><td>Description</td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=3">State</a></td>';
$sort_links .= '<td><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=5">Date Posted</a></td>';
}

return $sort_links;
}

// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
$page_links = '';

// If this page is not the first page, generate the "previous" link
if ($cur_page > 1) {
$page_links .= '<a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page - 1) . '"><-</a> ';
}
else {
$page_links .= '<- ';
}

// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= ' ' . $i;
}
else {
$page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . $i . '"> ' . $i . '</a>';
}
}

// If this page is not the last page, generate the "next" link
if ($cur_page < $num_pages) {
$page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page + 1) . '">-></a>';
}
else {
$page_links .= ' ->';
}

return $page_links;
}

// Grab the sort setting and search keywords from the URL using GET
$sort = $_GET['sort'];
$user_search = $_GET['usersearch'];

// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
$results_per_page = 5;  // number of results per page
$skip = (($cur_page - 1) * $results_per_page);

// Start generating the table of results
echo '<table border="0" cellpadding="2">';

// Generate the search result headings
echo '<tr class="heading">';
echo generate_sort_links($user_search, $sort);
echo '</tr>';

// Connect to the database
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

// Query to get the total results
$query = build_query($user_search, $sort);
$result = mysqli_query($dbc, $query);
$total = mysqli_num_rows($result);
$num_pages = ceil($total / $results_per_page);

// Query again to get just the subset of results
$query =  $query . " LIMIT $skip, $results_per_page";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<tr class="results">';
echo '<td valign="top" width="20%">' . $row['title'] . '</td>';
echo '<td valign="top" width="50%">' . substr($row['description'], 0, 100) . '...</td>';
echo '<td valign="top" width="10%">' . $row['state'] . '</td>';
echo '<td valign="top" width="20%">' . substr($row['date_posted'], 0, 10) . '</td>';
echo '</tr>';
}
echo '</table>';

// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
}

mysqli_close($dbc);
?>

</body>
</html>


/* style.css */

tr.heading {
color: #882E2C;
}

tr.results {
font-size: smaller;
color: #000000;
}

a {
text-decoration: none;
font-weight: bold;
}

a:link {
color: #882E2C;
}

a:hover {
background-color: #E2F345;
}
a:visited {
color: #882E2C;
}

a:active {
color: #000000;
}


[b]十. 正则表达式[/b]

1. 正则表达式是一些规则,用于匹配一个或多个串中的模式

2. 利用元字符可以在正则表达式中描述文本模式:

\d:匹配一位数字

\w:查找任何字母数字字符

\s:查找空白符(制表符,换行,回车符)

^:查找一个串的开始位置

.:点元字符可以匹配除了换行符以外的任意一个字符

[] 中的 \:‘或者’

\ … ?:…表示可选的内容

$:查找串尾

量词指定了一个元字符应当出现多少次;字符类是一组匹配单个字符的规则

3. 使用preg_match()检查模式:

例:preg_match(‘/^\d{3}-\d{2}-\d{4}$’,‘555-02-9983’);

使用preg_replace()函数可以取代串中的匹配文本:

例:$new_year=preg_replace(‘/200[0-9]’,‘2015’,‘Thisyear is 2014.’);

4. 通过标准化数据,可以得到更好的SQL查询结果

5. 验证通常是允许接受与实际接受之间的一个权衡

6. PHP checkdnsrr()函数检查一个域是否合法

7. 代码示例:
<!-- registration.php -->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Risky Jobs - Registration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<img src="riskyjobs_title.gif" alt="Risky Jobs" />
<img src="riskyjobs_fireman.jpg" alt="Risky Jobs" style="float:right" />
<h3>Risky Jobs - Registration</h3>

<?php
if (isset($_POST['submit'])) {
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$job = $_POST['job'];
$resume = $_POST['resume'];
$output_form = 'no';

if (empty($first_name)) {
// $first_name is blank
echo '<p class="error">You forgot to enter your first name.</p>';
$output_form = 'yes';
}

if (empty($last_name)) {
// $last_name is blank
echo '<p class="error">You forgot to enter your last name.</p>';
$output_form = 'yes';
}

if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9\._\-&!?=#]*@/', $email)) {
// $email is invalid because LocalName is bad
echo '<p class="error">Your email address is invalid.</p>';
$output_form = 'yes';
}
else {
// Strip out everything but the domain from the email
$domain = preg_replace('/^[a-zA-Z0-9][a-zA-Z0-9\._\-&!?=#]*@/', '', $email);
// Now check if $domain is registered
if (!checkdnsrr($domain)) {
echo '<p class="error">Your email address is invalid.</p>';
$output_form = 'yes';
}
}

if (!preg_match('/^\(?[2-9]\d{2}\)?[-\s]\d{3}-\d{4}$/', $phone)) {
// $phone is not valid
echo '<p class="error">Your phone number is invalid.</p>';
$output_form = 'yes';
}

if (empty($job)) {
// $job is blank
echo '<p class="error">You forgot to enter your desired job.</p>';
$output_form = 'yes';
}

if (empty($resume)) {
// $resume is blank
echo '<p class="error">You forgot to enter your resume.</p>';
$output_form = 'yes';
}
}
else {
$output_form = 'yes';
}

if ($output_form == 'yes') {
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>Register with Risky Jobs, and post your resume.</p>
<table>
<tr>
<td><label for="firstname">First Name:</label></td>
<td><input id="firstname" name="firstname" type="text" value="<?php echo $first_name; ?>"/></td></tr>
<tr>
<td><label for="lastname">Last Name:</label></td>
<td><input id="lastname" name="lastname" type="text" value="<?php echo $last_name; ?>"/></td></tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input id="email" name="email" type="text" value="<?php echo $email; ?>"/></td></tr>
<tr>
<td><label for="phone">Phone:</label></td>
<td><input id="phone" name="phone" type="text" value="<?php echo $phone; ?>"/></td></tr>
<tr>
<td><label for="job">Desired Job:</label></td>
<td><input id="job" name="job" type="text" value="<?php echo $job; ?>"/></td>
</tr>
</table>
<p>
<label for="resume">Paste your resume here:</label><br />
<textarea id="resume" name="resume" rows="4" cols="40"><?php echo $resume; ?></textarea><br />
<input type="submit" name="submit" value="Submit" />
</p>
</form>

<?php
}
else if ($output_form == 'no') {
echo '<p>' . $first_name . ' ' . $last_name . ', thanks for registering with Risky Jobs!<br />';
$pattern = '/[\(\)\-\s]/';
$replacement = '';
$new_phone = preg_replace($pattern, $replacement, $phone);
echo 'Your phone number has been registered as ' . $new_phone . '.</p>';

// code to insert data into the RiskyJobs database...
}
?>

</body>
</html>


/* style.css */

.error {
font-weight: bold;
color: #FF0000;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: