PHP学习练手(十一)


给脚本传值


1、方法一:利用HTML的隐藏输入框类型

<input type="hidden" name="do" value="this" />

在提交form表单时,$_POST[‘do’]将具有this这个值(假定表单使用POST方式)

2、把值追加到URL上

www.example.com/page.php?do=this

这种方式模仿了html表单的GET方法。

3、view_user3.php——该脚本能够展示Edit和Delete链接,并在每个url中传递一起传递用户的ID号

<?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 last_name, first_name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr, user_id 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>Edit</b></td>
                            <td align="left"><b>Delete</b></td>
                            <td align="left"><b>Last</b></td>
                            <td align="left"><b>First</b></td>
                            <td align="left"><b>Date Registered</b></td>
                        </tr>';
        while ($rows = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
            echo '<tr>
                            <td align="left"><a href="edit_user.php?id='.$rows['user_id'].'">Edit</a></td>
                            <td align="left"><a href="delete_user.php?id='.$rows['user_id'].'">Delete</a></td>
                            <td align="left">'.$rows['last_name'].'</td>
                            <td align="left">'.$rows['first_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');

?>

运行后:
这里写图片描述

知识点:

  • 为了把多个变量追加到URL中,可以使用下面这种语法:page.php?name1=value?&name2=value2&name3=value3…

  • 添加变量到url中的一种技巧是应该对字符串编码。以确保值会被正确处理。解决方案是使用urlencode()函数:
    $url = ‘page.php?’.urlencode(‘Elli Simth’);
    单提交表单时,GET方式会自动正确的执行。

4、delete_user.php——使用隐藏的表单输入框

<?php # Script 10.2 - delete_user.php
    $page_title = 'Delete a User';
    include ('../include/header.html');
    echo '<h1>Delete a User</h1>';

    if((isset($_GET['id'])) && (is_numeric($_GET['id'])))
    {
        $id = $_GET['id'];
    }elseif((isset($_POST['id'])) && (is_numeric($_POST['id'])))
    {
        $id = $_POST['id'];
    }else{
        echo '<p class="error">This page has been accessed in error.</p>';
        exit();
    }

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

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if($_POST['sure'] == 'Yes')
        {
            $sql = "DELETE FROM users WHERE user_id=$id LIMIT 1";
            $res = @mysqli_query($mysqli, $sql);
            if(mysqli_affected_rows($mysqli) == 1)
            {
                echo '<p>The user has been deleted</p>';
            }else{
            echo '<p class="error">The user could not be deleted due to a system.</p>';
            echo '<p>'.mysqli_error($mysqli).'<br/ >Query:'.$sql.'</p>';
          }
        }else{
            echo '<p>The user has NOT been deleted.</p>';
        }
    }else{
        $sql = "SELECT CONCAT(last_name, ',', first_name) FROM users WHERE user_id = $id";
        $res = @mysqli_query($mysqli, $sql);

        if(mysqli_num_rows($res) == 1)
        {
            $row = mysqli_fetch_array($res, MYSQLI_NUM);

            echo "<h3>Name: $row[0]</h3> 
                        Are you sure you want to delete this user?";

            echo '<form action="delete_user.php" method="post">
                            <input type="radio" name="sure" value="Yes"/>Yes
                            <input type="radio" name="sure" value="No" checked="checked"/>No
                            <input type="submit" name="submit" value="Submit"/>
                            <input type="hidden" name="id" value="'.$id.'"/>
                        </form>';
        }else{
            echo '<p class="error">This page has been accessed in error.</p>';
        }
    }

    mysqli_close($mysqli);

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

?>

当从如下图所示页面进入delete_user.php,会出现:
这里写图片描述

这里写图片描述

原因如下:

if((isset($_GET['id'])) && (is_numeric($_GET['id'])))
    {
        $id = $_GET['id'];
    }elseif((isset($_POST['id'])) && (is_numeric($_POST['id'])))
    {
        $id = $_POST['id'];
    }else{
        echo '<p class="error">This page has been accessed in error.</p>';
        exit();
    }

由于这种进入方式并没有提交表单,故直接进入到报错的echo中。。。

当从view_users3.php进入时,如下:
这里写图片描述

选择No,提交:
这里写图片描述

选择Yes,提交:
这里写图片描述

5、edit_user.php

<?php
    $page_title = 'Edit a User';
    include ('../include/header.html');
    echo '<h1>Edit a User</h1>';

    if((isset($_GET['id'])) && (is_numeric($_GET['id'])))
    {
        $id = $_GET['id'];
    }elseif((isset($_POST['id'])) && (is_numeric($_POST['id'])))
    {
        $id = $_POST['id'];
    }else{
        echo '<p class="error">This page has been accessed in error.</p>';
        exit();
    }

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

    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $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']));
        }

        if(empty($errors))
        {
            $sql = "SELECT user_id FROM users WHERE email= '$e' AND user_id != '$id'"; //判断提交的电子邮件地址是否尚未使用
            $res = @mysqli_query($mysqli, $sql);
            if(mysqli_num_rows($res) == 0) 
            {//若表中不存在该邮件使用者的ID,表明邮件尚未使用
                $sql = "UPDATE users SET first_name= '$fn', last_name= '$ln', email= '$e' WHERE user_id= $id LIMIT 1";
                $res = @mysqli_query($mysqli, $sql);
                if(mysqli_affected_rows($mysqli) == 1) //受影响记录条数
                {
                    echo '<p>The user has been edited.</p>';
                }else{
                    echo '<p>The user could not be edited due to a system error. We apologize for any inconvenience</p>';
                    echo '<p>'.mysqli_error($mysqli).'<br /><br />'.$sql.'</p>';
                }

            }else{
                echo '<p>The email address has been already been registered.</p>';
            }
        }//if_$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>';
        }

    }

    $sql = "SELECT first_name, last_name, email FROM users WHERE user_id = $id";
    $res= @mysqli_query($mysqli, $sql);

    if(mysqli_num_rows($res) == 1) //有效的用户ID
    {
        $rows = mysqli_fetch_array($res, MYSQLI_NUM);

        echo '<form action="edit_user.php" method="post">
                            <p>First Name: <input type="text" name="first_name" size="15" maxlength="15" value="'.$rows[0].'"/></p>
                            <p>Last Name: <input type="text" name="last_name" size="15" maxlength="30" value="'.$rows[1].'"/></p>
                            <p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="'.$rows[2].'"/></p>
                            <input type="submit" name="submit" value="Submit"/>
                            <input type="hidden" name="id" value="'.$id.'"/>
                        </form>';
    }else{
        echo '<p class="error">This page has been accessed in error.</p>';
    }

    mysqli_close($mysqli);

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

?>

从view_user3.php进入:
这里写图片描述

修改后提交:
这里写图片描述


给查询结果标页码


1、view_users4.php

<?php #Script 10.4 -view_users.php

    $page_title = 'View the Current Users';
    include('../include/header.html');
    echo '<h1>Registered Users</h1>';

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

    $display = 10;

    if(isset($_GET['p']) && is_numeric($_GET['p']))
    {
        $page = $_GET['p'];
    }else{
        $sql = "SELECT COUNT(user_id) FROM users"; //计算ID数目
        $res = @mysqli_query($mysqli, $sql);
        $row = @mysqli_fetch_array($res, MYSQLI_NUM);
        $records = $row[0];        //获取当前ID数目

        //当前ID数目多余每页显示的条数
        if($records > $display)
        {   
            //取不小于$records / $display的最小整数

            $page = ceil($records / $display); 
        }else{
            $page = 1;
        }

    }

    //调取数据的起始位置
    if(isset($_GET['s']) && is_numeric($_GET['s']))
    {
        $start = $_GET['s'];
    }else{
        $start = 0;
    }

    $sql = "SELECT last_name, first_name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr, user_id FROM users ORDER BY registration_date ASC LIMIT $start, $display";
    $res = @mysqli_query($mysqli, $sql);
    echo '<table border="1" cellspacing="0" cellpadding="10" align="center">
                    <tr>
                        <td align="left"><b>Edit</b></td>
                        <td align="left"><b>Delete</b></td>
                        <td align="left"><b>Last Name</b></td>
                        <td align="left"><b>First Name</b></td>
                        <td align="left"><b>Date Registered</b></td>
                    </tr>
                ';

    $bg = '#eee';

    while($rows = mysqli_fetch_array($res, MYSQLI_ASSOC))
    {
        $bg = ($bg == '#eee' ? '#fff' : '#eee');
        echo '<tr bgcolor="'.$bg.'">
                        <td align = "letf"><a href="edit_user.php?id='.$rows['user_id'].'">Edit</a></td>
                        <td align = "letf"><a href="delete_user.php?id='.$rows['user_id'].'">Delete</a></td>
                        <td align="left">'.$rows['last_name'].'</td>
                        <td align="left">'.$rows['first_name'].'</td>
                        <td align="left">'.$rows['dr'].'</td>
                    </tr>';
    }

    echo '</table>';

    mysqli_free_result($res);
    mysqli_close($mysqli);

    if($page > 1)
    {
        echo '<br/><p>';
        $current_page = ($start / $display) + 1;   //当前该显示的页数
        if($current_page != 1) //当前显示页大于1
        {
            echo '<a href="view_users4.php?s='.($start - $display).'&p='.$page.'">Previous </a>';
        }

        for($i = 1; $i <= $page; $i++)
        {
            if($i != $current_page)
            {
                echo '<a href="view_users4.php?s='.(($display*($i-1))).'&p='.$page.'">'.$i.' </a>';
            }else{
                echo $i.' ';
            }
        }

        if($current_page != $page)
        {
            echo '<a href="view_users4.php?s='.($start+$display).'&p='.$page.'"> Next</a>';
        }
        echo '</p>';
    }//if_$page>1

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

?>

代码解析:

if($records > $display)
        {   
            //取不小于$records / $display的最小整数

            $page = ceil($records / $display); 
        }else{
            $page = 1;
        }

——上述$page表示当前数据中的数据一共可以显示成多少个页面。

if($current_page != 1) //当前显示页大于1
        {
            echo '<a href="view_users4.php?s='.($start - $display).'&p='.$page.'">Previous </a>';
        }

——如果当前页面不是第一个页面(即页码>1),它还需要一个Previous连接,指向早期的结果集。前一页的起点将是当前起点减去要显示的数量。

for($i = 1; $i <= $page; $i++)
        {
            if($i != $current_page)
            {
                echo '<a href="view_users4.php?s='.(($display*($i-1))).'&p='.$page.'">'.$i.' </a>';
            }else{
                echo $i.' ';
            }
        }

——通过1到页面的总数的循环来创建一批连接,除了当前页面外,其余的页面均会被链接

if($current_page != $page)
        {
            echo '<a href="view_users4.php?s='.($start+$display).'&p='.$page.'"> Next</a>';
        }

——如果当前页面不是最终页面,则存在一个Next链接到下页面。

运行后如下:
这里写图片描述

这里写图片描述


建立可排序的显示结果


1、view_users5.php

<?php #Script 10.4 -view_users.php

    $page_title = 'View the Current Users';
    include('../include/header.html');
    echo '<h1>Registered Users</h1>';

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

    $display = 10;

    if(isset($_GET['p']) && is_numeric($_GET['p']))
    {
        $page = $_GET['p'];
    }else{
        $sql = "SELECT COUNT(user_id) FROM users"; //计算ID数目
        $res = @mysqli_query($mysqli, $sql);
        $row = @mysqli_fetch_array($res, MYSQLI_NUM);
        $records = $row[0];        //获取当前ID数目

        //当前ID数目多余每页显示的条数
        if($records > $display)
        {   
            //取不小于$records / $display的最小整数

            $page = ceil($records / $display); 
        }else{
            $page = 1;
        }

    }

    //调取数据的起始位置
    if(isset($_GET['s']) && is_numeric($_GET['s']))
    {
        $start = $_GET['s'];
    }else{
        $start = 0;
    }

    //设置查询顺序
    $sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'rd';

    switch($sort)
    {
        case 'ln':
            $order_by = 'last_name ASC';
            break;
        case 'fn':
            $order_by = 'first_name DESC';
            break;
        case 'rd':
            $order_by = 'registration_date DESC';
            break;
        default:
            $order_by = 'registration_date ASC';
            $sort = 'rd';
            break;
    }

    $sql = "SELECT last_name, first_name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr, user_id FROM users ORDER BY $order_by LIMIT $start, $display";

    /*$sql = "SELECT last_name, first_name, DATE_FORMAT(registration_date, '%M %d, %Y') AS dr, user_id FROM users ORDER BY registration_date ASC LIMIT $start, $display";*/
    $res = @mysqli_query($mysqli, $sql);

    echo '<table border="1" cellspacing="0" cellpadding="10" align="center">
                    <tr>
                        <td align="left"><b>Edit</b></td>
                        <td align="left"><b>Delete</b></td>
                        <td align="left"><b><a href="view_users5.php?sort=rn">Last Name</a></b></td>
                        <td align="left"><b><a href="view_users5.php?sort=fn">First Name</a></b></td>
                        <td align="left"><b><a href="view_users5.php?sort=rd">Date Registered</a></b></td>
                    </tr>
                ';

    $bg = '#eee';

    while($rows = mysqli_fetch_array($res, MYSQLI_ASSOC))
    {
        $bg = ($bg == '#eee' ? '#fff' : '#eee');
        echo '<tr bgcolor="'.$bg.'">
                        <td align = "letf"><a href="edit_user.php?id='.$rows['user_id'].'">Edit</a></td>
                        <td align = "letf"><a href="delete_user.php?id='.$rows['user_id'].'">Delete</a></td>
                        <td align="left">'.$rows['last_name'].'</td>
                        <td align="left">'.$rows['first_name'].'</td>
                        <td align="left">'.$rows['dr'].'</td>
                    </tr>';
    }

    echo '</table>';

    mysqli_free_result($res);
    mysqli_close($mysqli);

    if($page > 1)
    {
        echo '<br/><p>';
        $current_page = ($start / $display) + 1;   //当前该显示的页数
        if($current_page != 1) //当前显示页大于1
        {
            /*echo '<a href="view_users4.php?s='.($start - $display).'&p='.$page.'&">Previous </a>';*/
            echo '<a href="view_users5.php?s='.($start - $display).'&p='.$page.'&sort='.$sort.'">Previous </a>';
        }

        for($i = 1; $i <= $page; $i++)
        {
            if($i != $current_page)
            {
                echo '<a href="view_users5.php?s='.(($display*($i-1))).'&p='.$page.'&sort='.$sort.'">'.$i.' </a>';
            }else{
                echo $i.' ';
            }
        }

        if($current_page != $page)
        {
            echo '<a href="view_users5.php?s='.($start+$display).'&p='.$page.'&sort='.$sort.'"> Next</a>';
        }
        echo '</p>';
    }//if_$page>1

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

?>

这里写图片描述

<td align="left"><b><a href="view_users5.php?sort=rn">Last Name</a></b></td>
                        <td align="left"><b><a href="view_users5.php?sort=fn">First Name</a></b></td>
                        <td align="left"><b><a href="view_users5.php?sort=rd">Date Registered</a></b></td>

——给标题添加排序链接,点击First Name运行如下:
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值