1. 程式人生 > >PHP學習練手(十一)

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執行如下:
這裡寫圖片描述