Extends from the last chapter , This chapter takes a look at some real-world problems that can occur as you move your application

from testing to a live website, Through this chapter you will learn more important PHP and SQL code.

First Problem : Its never safe to assume a web form will be used exactly the way it was intended.

        SO try and head off these kinds of problems by anticipating that some users will misuse your forms.

So the form is in need of validation, which is the process of checking to make sure form data is OK before doing anything with it.

 Validation means making the data you get is the data you expect . 

Just a tip here: you can also validating data on the client by JavaScript. But the server is the last line of defense for catching bad form data,

So server-side validation can't be ignored even if you have checked the data on the client-side.

Above the last project, we should add some code to sendemail.php that examines the values in the text boxes and checks to make

sure they aren't empty. If everything checks out OK, the script sends out the emails.

A form that references itself. An HTML form that is part of the PHP script that process it is known as self-referencing.(自引用表格,表格会提交到自身)

When a form is smart enough to remember data entered into it in prior submissions, its know as a sticky form, data sticks to it!

you can make the sendemail.php a self-referencing form like this :

<form action="sendemail.php" method="post">

or you can do it like this :

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

superglobal variable $_SERVER['PHP_SELF'], which stores the name of the current script. You can replace the script URL in the form action to

$_SERVER['PHP_SELF'], and not ever have to worry about updating anything if you ever need to rename the script.

To make the form Validation and Sticky , you can edit the sendemail.php like this :

 <!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>Make Me Elvis - Send Email</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<img src="blankface.jpg" width="161" height="350" alt="" style="float:right" />
<img name="elvislogo" src="elvislogo.gif" width="229" height="32" border="0" alt="Make Me Elvis" />
<p><strong>Private:</strong> For Elmer's use ONLY<br />
Write and send an email to mailing list members.</p> <?php
if (isset($_POST['submit'])) {
$from = 'elmer@makemeelvis.com';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$output_form = false; if (empty($subject) && empty($text)) {
// We know both $subject AND $text are blank
echo 'You forgot the email subject and body text.<br />';
$output_form = true;
} if (empty($subject) && (!empty($text))) {
echo 'You forgot the email subject.<br />';
$output_form = true;
} if ((!empty($subject)) && empty($text)) {
echo 'You forgot the email body text.<br />';
$output_form = true;
}
}
else {
$output_form = true;
} if ((!empty($subject)) && (!empty($text))) {
$dbc = mysqli_connect("localhost","root","root","elvis_store")
or die("Error connectiong to MySQL");
echo "Connecting success! </br>"; $query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query)
or die("Error querying database!");
echo "Quering success! </br>"; while( $row = mysqli_fetch_array($result) ) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$to = $row['email']; $msg = "Dear $first_name $last_name, \n $text"; mail($to, $subject, $msg, 'From: '.$from ); echo 'Emai sent to :'.$to. "<br/>";
}
mysqli_close($dbc);
} if ($output_form) {
?> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="subject">Subject of email:</label><br />
<input id="subject" name="subject" type="text" value="<?php echo $subject; ?>" size="30" /><br />
<label for="elvismail">Body of email:</label><br />
<textarea id="elvismail" name="elvismail" rows="8" cols="40"><?php echo $text; ?></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form> <?php
}
?> </body>
</html>

Next we should the alter the table to make table rows should be uniquely identifialbe.

SQL has a command that lets you make changes to an existing table without losing any data.

ALTER TABLE table_name ADD column_name column_type

you can use it like this :

ALTER TABLE email_list ADD id INT NOT NULL AUTO_INCREMENT FIRST,

ADD PRIMARY KEY(id)  #this little chunk of code tells MySQL that new id column is the primary key for the table, you can learn more detail here

After you have changed the database, you should also add validation to the addemail.php just like what we did before:

<?
/**
* Created by IntelliJ IDEA.
* User: beyond_acm
* Date: 9/1/2015
* Time: 9:58 AM
*/
?> <!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>Make Me Elvis - Add Email</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<img src="blankface.jpg" width="161" height="350" alt="" style="float:right" />
<img name="elvislogo" src="elvislogo.gif" width="229" height="32" border="0" alt="Make Me Elvis" />
<p>Enter your first name, last name, and email to be added to the <strong>Make Me Elvis</strong> mailing list.</p> <?php
if( isset($_POST['submit']) ) {
// if submit the form
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$output_form = 'no';
//TODO the validation
if (empty($first_name) || empty($last_name) || empty($email)) {
// We know at least one of the input fields is blank
echo 'Please fill out all of the email information.<br />';
$output_form = 'yes';
}
} else {
$output_form = 'yes';
}
//If the form is validate, then todo insert the data into the database
if (!empty($first_name) && !empty($last_name) && !empty($email)) {
$dbc = mysqli_connect('localhost', 'root', 'root', 'elvis_store')
or die('Error connecting to MySQL server.'); $query = "INSERT INTO email_list (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die ('Data not inserted.'); echo 'Customer added.'; mysqli_close($dbc);
}
if ($output_form == 'yes') {
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" /><br />
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" /><br />
<label for="email">Email:</label>
<input type="text" id="email" name="email" /><br />
<input type="submit" name="submit" value="Submit" />
</form> <?php
}
?> </body>
</html>

Last we should add a removeemail.php to delete users from the table, the removeemail.php is as followed :

<?
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 9/1/2015
* Time: 10:29 AM
*/
?> <!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>Make Me Elvis - Remove Email</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<img src="blankface.jpg" width="161" height="350" alt="" style="float:right" />
<img name="elvislogo" src="elvislogo.gif" width="229" height="32" border="0" alt="Make Me Elvis" />
<p>Please select the email addresses to delete from the email list and click Remove.</p> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$dbc = mysqli_connect('localhost', 'root', 'root', 'elvis_store')
or die('Error connecting to MySQL server'); //Delete the customer rows (only if the form has been submitted)
if( isset($_POST['submit']) ) {
foreach( $_POST['todelete'] as $delete_id ) {
$query = "DELETE FROM email_list WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error quering database');
}
echo 'Customer(s) removed. </br>';
} //Display the customer rows with checkboxed for deleting
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query);
while( $row = mysqli_fetch_array($result) ) {
echo '<input type="checkbox" value=' .$row['id']. ' name="todelete[]" />';
echo $row['first_name'];
echo ' '.$row['last_name'];
echo ' '.$row['email'];
echo '</br>';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="Remove">
</form> </body>
</html>

if you get it right, you should see some pages as follows :

Now you can delete the registerd user stored in the database, Cool you have finished a real webapp.

#2 create and populate a database && realistic and practical applications (PART 2)的更多相关文章

  1. #2 create and populate a database && realistic and practical applications

    The Chapter3 & Chapter4 of this book tells you how to create a realistic app on the web through ...

  2. Create a SQL Server Database on a network shared drive

    (原文地址:http://blogs.msdn.com/b/varund/archive/2010/09/02/create-a-sql-server-database-on-a-network-sh ...

  3. [转]How to: Create a Report Server Database (Reporting Services Configuration)

    本文转自:https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms157300%28v%3dsql.10 ...

  4. Create an Azure SQL database in the Azure portal

    Create a SQL database An Azure SQL database is created with a defined set of compute and storage res ...

  5. [Windows Azure] How to Create and Configure SQL Database

    How to Create and Configure SQL Database In this topic, you'll step through logical server creation ...

  6. HiveSQLException: Error while compiling statement: No privilege 'Create' found for outputs { database:default }

    今天用Hive的JDBC实例时出现了HiveSQLException: Error while compiling statement: No privilege 'Create' found for ...

  7. [odb-users] Create schema error (unknown database schema '')

    Boris Kolpackov boris at codesynthesis.comFri May 31 11:13:02 EDT 2013 Previous message: [odb-users] ...

  8. [置顶] How to create Oracle 11g R2 database manually in ASM?

    Step 1: Specify an Instance Identifier (SID) export ORACLE_SID=maomi Step 2: Ensure That the Require ...

  9. Create schema error (unknown database schema '')

    Andrey Devyatka 4 years ago Permalink Raw Message Hi,Please tell me, can I use the static library in ...

随机推荐

  1. 判断dataset表中是否存在 某列

    DataSet ds ; ds.Tables[0].Columns.Contains("a") 同样适用于 datarow dr ; dr.Table.Columns.Contai ...

  2. java如何导入Excel文件

    Java使用POI导入Excel文件,操作起来比较简单,支持xlsx格式. 下载POI资源包 从官网https://poi.apache.org/下载POI,笔者选择的是版本是3.17,下载后文件名是 ...

  3. AngularJS(十):依赖注入

    本文也同步发表在我的公众号“我的天空” 依赖注入 依赖注入不是AngularJS独有的概念,而是现代软件开发与架构的范畴,但是在AngularJS中“依赖注入”是其核心思想之一,所以我们专门来学习一下 ...

  4. 超链接显示网站 A,访问后进入网站 B

    #前端黑魔法# 出一个思考题:如何用最少的字符实现下图效果.即超链接显示网站 A,访问后进入网站 B. 当然这个是上古时代的黑魔法了,稍懂前端的都知道原理.所以这里只问最短的实现~ 一个简单的演示:( ...

  5. ArcMap中提取影像数据边界

    1.前言 客户手里有一些经过裁剪的不规则多边形影像数据(如图例所示),希望能批量获取该类影像的边界信息,即影像对应的面信息,边界线信息.这里我们提供一种利用镶嵌数据集Footprint图层的方法来获取 ...

  6. Java中对jsonArray的排序,使用的是Gson

    使用Gson对json解析字符串,转化为json对象. 先上代码: 下面是main方法里面的代码 package testJava; import java.util.ArrayList; impor ...

  7. 消除ImageButton背景图片

    下图被选为作为ImageButton的Src,可它自带了个灰色的背景图,而我只想用这个圆圈作为imageButton的src,这怎么办呢? 遇到此情况可以设置imagebutton的backgroun ...

  8. [Java]在xp系统下java调用wmic命令获取窗口返回信息无反应(阻塞)的解决方案

    背景:本人写了一段java代码,调用cmd命令“wmic ...”来获取系统cpu.mem.handle等资源信息.在win7操作系统下运行没有问题,在xp系统下却发现读取窗口反馈信息时无反应(阻塞) ...

  9. Linux让Apache支持中文URL图片/文件名

    需要用到iconv_hook和mod_encoding Apache(32位): 安装环境:CentOS 5.6 + Apache 2.2.15 (Apache2.4同样适用) 安装结果:安装后支持“ ...

  10. 微信小程序 尺寸单位px与rpx之间的转换(入门篇)

    1.rpx:微信小程序中的尺寸单位rpx(responsive pixel):可以根据屏幕宽度进行自适应.规定屏幕宽度为750rpx. 微信官方建议视觉稿以iphone6为标准. 2.个人示例测试: ...