PHP学习练手(十)

模板

  • header.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $page_title; ?></title>
    <link rel="stylesheet" href="../include/style.css" type="text/css" media = "screen">
</head>
<body>
    <div id="header">
        <h1>Your Website</h1>
        <h2>catchy slogan...</h2>
    </div>
    <div id="navigation">
        <ul>
            <li><a href="index.php">Home Page</a></li>
            <li><a href="register.php">Register</a></li>
            <li><a href="view_users.php">View Users</a></li>
            <li><a href="password.php">Change Password</a></li>
            <li><a href="#">link five</a></li>
        </ul>
    </div>
    <div id="content"><!-- Start of the page-specific content-->
    <!-- Script 9.1 - header.html -->
  • footer.html:
<!-- Script 3.3 - footer.html-->
    <!-- End of the page-specific content. -->
    </div>
    <div id="footer">
        <p>Coryright $copy; <a href="#">Plain and Simple</a> 2015 | Designed by <a href="http://www.edg3.co.uk"></a> | Sponsored by <a href="http://www.opendesigns.org/">OpenDesigns</a> | Valid <a href="http://jigsaw.w3.org/css-validator">CSS</a> &amp; <a href="http://validator.w3.org">XHTML</a></p>
    </div>
</body>
</html>
  • mysqli_connect.php:
<?php # Script 9.2 - mysqli_connect.php

DEFINE ('DB_USER', 'XXX');  //填写自己数据库的用户名
DEFINE ('DB_PASSWORD', 'XXX');  //填写自己数据库的密码
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'sitename');

//连接数据库
$mysqli = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL:'.mysqli_connect_error());

//设置数据库字符编码
mysqli_set_charset($mysqli, 'utf8');

知识点:

  • mysqli_connect()——连接到服务器

  • mysqli_connect_error()——如果发生连接错误,它返回连接错误消息,不带参数

  • 在函数调用之前放置一个错误控制运算符(@),可以防止在web浏览器中显示PHP错误。这是一种首选的做法,因为错误将由OR die()子句处理。

  • 因为mysqli_connect.php包含敏感的MySQL访问信息,故将其存储在与htdocs同一级目录上,这样就不能从Web浏览器访问该文件。

    这里写图片描述

  • register.php

<?php # Script 9.3 - register.php

    $page_title = 'Register';
    include ('../include/header.html');

    //检查提交状态
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $errors = array();     //存储错误信息

        //检查first name
        if(empty($_POST['first_name']))
        {
            $errors[] = 'You forgot to enter your first name';
        }else{
            $fn = trim($_POST['first_name']);
        }

        //检查last name
        if (empty($_POST['last_name'])) 
        {

            $errors[] = 'You forgot to enter your last name';
        }else{
            $ln = trim($_POST['last_name']);
        }

        //检查email Address
        if (empty($_POST['email'])) 
        {

            $errors[] = 'You forgot to enter your email';
        }else{
            $e = trim($_POST['email']);
        }

        //检查password 和 confirm password
        if (!empty($_POST['pass1'])) 
        {

            if ($_POST['pass1'] != $_POST['pass2']) 
            {
                $errors[] = 'Your password did not match the confirm password';
            }else{
                $p = trim($_POST['pass1']);
            }   
        }else{
            $errors[] = 'You forgot to enter your password';
        }

        //检查是否存在错误
        if (empty($errors)) {  //无误
            //连接数据库
            require ('../mysqli_connect.php');

            //执行insert操作
            $sql = "INSERT INTO users(first_name, last_name, email, pass, registration_date) VALUES (
                                                        '$fn', '$ln', '$e', SHA1('$p'), NOW()
                                                        )";
            $res = @mysqli_query($mysqli, $sql);
            if($res)   //插入成功
            {
                echo '<h1>Thank you!</h1>
                            <p>You are now registered. In Chapter 12 you will actually be able to login in!</p><p><br/></p>';

            }else{  //插入失败
                echo '<h1>System Error</h1>
                            <p class="error">You could not be registered due to a system error. We apologize for any inconvenience</p>';
                echo '<p>'.mysqli_error($mysqli).'<br /><br />'.$sql.'</p>';
            }

            mysqli_close($mysqli); //关闭数据库

            include ('../include/footer.html');
            exit();

        }else{  //有误
            echo '<h1>Error!</h1>
                        <p class="error">The following error(s) occured:<br/ >';
            foreach ($errors as $msg) {
                echo "- $msg<br/ >";
            }
            echo '</p><p>Please try again</p><p><br/ ></p>';

        }

    }

?>
<h1>Register</h1>
<form action="register.php" method="post">
        <p>First Name: <input type="text" name="first_name" size="15" maxlength="20" value="<?php if(isset($_POST['first_name'])) echo $_POST['first_name']; ?>" /></p>
        <p>Last Name: <input type="text" name="last_name" size="15" maxlength="40" value="<?php if(isset($_POST['last_name'])) echo $_POST['last_name']; ?>" /></p>
        <p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" /></p>
        <p>Password: <input type="password" name="pass1" size="10" maxlength="20" value="<?php if(isset($_POST['pass1'])) echo $_POST['pass1']; ?>" /></p>
        <p>Confirm Password: <input type="password" name="pass2" size="10" maxlength="20" value="<?php if(isset($_POST['pass2'])) echo $_POST['pass2']; ?>" /></p>
        <p><input type="submit" name="submit" value="Register" /></p>
</form>
<?php include ('../include/footer.html')?>
  • 在浏览器中输入register.php的url,结果如图

    这里写图片描述

  • 提交之后,如图

    这里写图片描述

  • 假设某一信息没填,如图

    这里写图片描述

  • view_users.php

<?php #Script 9.4 -view_users.php

    $page_title = 'View the Current Users';
    include ('../include/header.html');

    echo '<h1>Registered Users</h1>';

    require ('../mysqli_connect.php');

    $sql = "SELECT CONCAT(last_name, ',', first_name) AS name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr FROM users ORDER BY registration_date ASC";

    $res = @mysqli_query ($mysqli, $sql);

    if($res)
    {
        echo '<table align="center" cellspacing="3" width="75%">
                        <tr><td align="left"><b>Name</b></td><td align="left"><b>Date Registered</b></td></tr>';
        while ($rows = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
            echo '<tr><td align="left">'.$rows['name'].'</td><td align="left">'.$rows['dr'].'</td></tr>';
        }
        echo '</table>';

        mysqli_free_result($res);  //释放掉资源
    }//if_$res
    else{
        echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';

        echo '<p>'.mysqli_error($mysqli).'<br/ ><br/ >Query: '.$sql.'</p>';
    }

    mysqli_close($mysqli);

    include ('../include/footer.html');

?>
  • 运行之后
    这里写图片描述

知识点:

  • mysqli_fetch_array([参数]):它带有一个查询结果变量,以数组个数返回一行数据,采用循环,可以返回多行数据。

  • mysqli_free_result ( res) res占用的系统开销

  • mysqli_fetch_array()与 mysqli_fetch_array($res, MYSQLI_NUM)等价

  • mysqli_fetch_assoc()与mysqli_fetch_array($res,MYSQLI_ASSOC)等价

  • 参数:
    1、MYSQLI_ASSOC: 返回关联数组形式,如$rows['column']
    2、MYSQLI_NUM: 返回索引数组形式,如$rows[0],与参数不填作用相同。比MYSQLI_ASSOC要快一点,且占用内存少些。
    3、MYSQLI_BOTH: 返回关联和索引2种形式

    • register2.php——register的安全版
<?php # Script 9.3 - register.php

    $page_title = 'Register';
    include ('../include/header.html');

    //检查提交状态
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        //连接数据库
        require ('../mysqli_connect.php');

        $errors = array();     //存储错误信息

        //检查first name
        if(empty($_POST['first_name']))
        {
            $errors[] = 'You forgot to enter your first name';
        }else{
            $fn = mysqli_real_escape_string($mysqli, trim($_POST['first_name']));
        }

        //检查last name
        if (empty($_POST['last_name'])) 
        {

            $errors[] = 'You forgot to enter your last name';
        }else{
            $ln = mysqli_real_escape_string($mysqli, trim($_POST['last_name']));
        }

        //检查email Address
        if (empty($_POST['email'])) 
        {

            $errors[] = 'You forgot to enter your email';
        }else{
            $e = mysqli_real_escape_string($mysqli, trim($_POST['email']));
        }

        //检查password 和 confirm password
        if (!empty($_POST['pass1'])) 
        {

            if ($_POST['pass1'] != $_POST['pass2']) 
            {
                $errors[] = 'Your password did not match the confirm password';
            }else{
                $p = mysqli_real_escape_string($mysqli, trim($_POST['pass1']));
            }   
        }else{
            $errors[] = 'You forgot to enter your password';
        }

        //检查是否存在错误
        if (empty($errors)) {  //无误


            //执行insert操作
            $sql = "INSERT INTO users(first_name, last_name, email, pass, registration_date) VALUES (
                                                        '$fn', '$ln', '$e', SHA1('$p'), NOW()
                                                        )";
            $res = @mysqli_query($mysqli, $sql);
            if($res)   //插入成功
            {
                echo '<h1>Thank you!</h1>
                            <p>You are now registered. In Chapter 12 you will actually be able to login in!</p><p><br/></p>';

            }else{  //插入失败
                echo '<h1>System Error</h1>
                            <p class="error">You could not be registered due to a system error. We apologize for any inconvenience</p>';
                echo '<p>'.mysqli_error($mysqli).'<br /><br />'.$sql.'</p>';
            }

            mysqli_close($mysqli); //关闭数据库

            include ('../include/footer.html');
            exit();

        }else{  //有误
            echo '<h1>Error!</h1>
                        <p class="error">The following error(s) occured:<br/ >';
            foreach ($errors as $msg) {
                echo "- $msg<br/ >";
            }
            echo '</p><p>Please try again</p><p><br/ ></p>';

        }

        mysqli_close($mysqli); //关闭数据库

    }

?>
<h1>Register</h1>
<form action="register2.php" method="post">
        <p>First Name: <input type="text" name="first_name" size="15" maxlength="20" value="<?php if(isset($_POST['first_name'])) echo $_POST['first_name']; ?>" /></p>
        <p>Last Name: <input type="text" name="last_name" size="15" maxlength="40" value="<?php if(isset($_POST['last_name'])) echo $_POST['last_name']; ?>" /></p>
        <p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" /></p>
        <p>Password: <input type="password" name="pass1" size="10" maxlength="20" value="<?php if(isset($_POST['pass1'])) echo $_POST['pass1']; ?>" /></p>
        <p>Confirm Password: <input type="password" name="pass2" size="10" maxlength="20" value="<?php if(isset($_POST['pass2'])) echo $_POST['pass2']; ?>" /></p>
        <p><input type="submit" name="submit" value="Register" /></p>
</form>
<?php include ('../include/footer.html')?>
  • 注册新用户,如图
    这里写图片描述

    这里写图片描述

  • 知识点:

    • mysqli_real_escape_string($mysqli, data):转义那些可能有问题的字符来清理数据。

    • 如果在服务器上启用Magic Quotes,那么在使用mysqli_real_escape_string()函数之前,需要删除Magic Quotes添加的任何斜杠,采用stripslashes()函数。

  • view_users2.php

<?php #Script 9.4 -view_users.php

    $page_title = 'View the Current Users';
    include ('../include/header.html');

    echo '<h1>Registered Users</h1>';

    require ('../mysqli_connect.php');

    $sql = "SELECT CONCAT(last_name, ',', first_name) AS name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr FROM users ORDER BY registration_date ASC";

    $res = @mysqli_query ($mysqli, $sql);

    $nums = mysqli_num_rows($res);
    if($nums > 0)
    {
        echo "<p>There are currently $nums registered users</p>";

        echo '<table align="center" cellspacing="3" width="75%">
                        <tr><td align="left"><b>Name</b></td><td align="left"><b>Date Registered</b></td></tr>';
        while ($rows = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
            echo '<tr><td align="left">'.$rows['name'].'</td><td align="left">'.$rows['dr'].'</td></tr>';
        }
        echo '</table>';
        mysqli_free_result($res);  //释放掉资源

    }//if_$nums
    else{
        echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';

        echo '<p>'.mysqli_error($mysqli).'<br/ ><br/ >Query: '.$sql.'</p>';
    }

    mysqli_close($mysqli);

    include ('../include/footer.html');

?>
  • 运行

    这里写图片描述

  • 知识点:

    • mysqli_num_rows($res):返回select查询检索的行数,并将查询结果变量作为一个参数返回,可以用在分页显示查询结果中
  • password.php

<?php

$page_title = 'Change your Password';
include ('../include/header.html');

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    require('../mysqli_connect.php');

    $errors = array(); //存储错误信息

    //检查email
    if(empty($_POST['email']))
    {
        $errors = 'You forget to enter your email address';
    }else{
        $e = mysqli_real_escape_string($mysqli, trim($_POST['email']));
    }

    //检查current password
    if(empty($_POST['pass']))
    {
        $errors = 'You forget to enter your current password';
    }else{
        $p = mysqli_real_escape_string($mysqli, trim($_POST['pass']));
    }

    //检查new password
    if (!empty($_POST['pass1'])) 
    {

            if ($_POST['pass1'] != $_POST['pass2']) 
            {
                $errors[] = 'Your new password did not match the confirm password';
            }else{
                $np = mysqli_real_escape_string($mysqli, trim($_POST['pass1']));
            }   
        }else{
            $errors[] = 'You forgot to enter your new password';
    }

    if(empty($errors))
    {
        $sql = "SELECT user_id FROM users WHERE (email='$e' AND pass=SHA1('$p'))";
        $res = @mysqli_query($mysqli, $sql);
        $nums = mysqli_num_rows($res);
        if($nums == 1)
        {
            $row = mysqli_fetch_array($res, MYSQLI_NUM);
            $sql = "UPDATE users SET pass=SHA1('$np') WHERE user_id = $row[0]";
            $res = @mysqli_query($mysqli, $sql);

            if(mysqli_affected_rows($mysqli) == 1)
            {
                echo '<h1>Thank you!</h1>
                            <p>Your password has been updated. In Chapter 12 you will actually be able to login in!</p><p><br/></p>';
            }else{
                echo '<h1>Thank you!</h1>
                            <p class="error">Your password could not be changed due to a system error, We apologize for any inconvenience.</p>';
                echo '<p>'.mysqli_error($mysqli).'<br /><br />'.$sql.'</p>';
            }

            mysqli_close($mysqli);

            include('../include/footer.html');
            exit();
        }//if_$nums
        else{
            echo '<h1>Error!</h1>
                        <p class="error">The email address and password do not match those on file.<br/ ></p>';
        }
    }//if_empty($errors)
    else{
        echo '<h1>Error!</h1>
                        <p class="error">The following error(s) occured:<br/ >';
        foreach ($errors as $msg) {
            echo "- $msg<br/ >";
        }
        echo '</p><p>Please try again</p><p><br/ ></p>';
    }
    mysqli_close($mysqli);
}

?>
<h1>Change Your Password</h1>
<form action="password.php" method="post">
        <p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" /></p>
        <p>Current Password: <input type="password" name="pass" size="10" maxlength="20" value="<?php if(isset($_POST['pass'])) echo $_POST['pass1']; ?>" /></p>
        <p>New Password: <input type="password" name="pass1" size="10" maxlength="20" value="<?php if(isset($_POST['pass1'])) echo $_POST['pass1']; ?>" /></p>
        <p>Confirm Password: <input type="password" name="pass2" size="10" maxlength="20" value="<?php if(isset($_POST['pass2'])) echo $_POST['pass2']; ?>" /></p>
        <p><input type="submit" name="submit" value="Register" /></p>
</form>

<?php include ('../include/footer.html'); ?>
  • 用于修改当前密码

    这里写图片描述

    这里写图片描述

  • 知识点:

如果使用命令TRUNCATE tablename
从表中删除所有记录,则mysqli_affected_rows()会返回0,即使查询成功执行并删除了每一行

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值