Week 9 —— PHP Data Objects (PDO)

PHP Data Objects (PDO)

本节主要讲用PHP来实现数据库的基本操作。

  • php编程实现数据库的读取
  • php编程实现数据库的插入
  • php编程实现数据库的更新
  • php编程实现数据库的删除
  • php编程实现数据库的搜索

下述实验用的数据库名为:ebookingsdb。用户名为:root。密码为空。

内置三个表:
在这里插入图片描述
bookings:
在这里插入图片描述
invitations:
在这里插入图片描述
users:
在这里插入图片描述

Lab9.1 - Read Records using PDO

读取数据库数据

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        $dsn = 'mysql:host=localhost;dbname=ebookingsdb';
        $usename = 'root';
        $password = '';
        $conn = new PDO($dsn,$usename,$password);
        $sql = 'select * from bookings';
        $statement = $conn->query($sql);
        $records = $statement->fetchAll();
        print_r($records);
        
        $sql = 'select * from invitations';
        $statement = $conn->query($sql);
        $records = $statement->fetchAll();
        print_r($records);
        
        $sql = 'select * from users';
        $statement = $conn->query($sql);
        $records = $statement->fetchAll();
        print_r($records);
        ?>
    </body>
</html>

Lab9.2 - Insert Records using PDO

往数据库里插入数据

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        //Insert bookings
        $values = [4, 'Penny', 'Smith', '[email protected]', '1/10/2019', '12:30:00', 500, 2];
        $dsn = 'mysql:host=localhost;dbname=ebookingsdb';
        $username = 'root';
        $password = '';
        $conn = new PDO($dsn, $username, $password);
        $sql = "insert into bookings (booking_id,first_name,last_name,email,booking_date,booking_time,num_people,user_id)values(?,?,?,?,?,?,?,?)";
        $statement = $conn->prepare($sql);
        $success = $statement->execute($values);
        if ($success) {
            echo"Insert booking record successed!";
        } else {
            echo"Insert booking record failed!";
        }
        echo '<br>';
        //Insert invitations
        $values = [27, 'whh', '454578962', 'whh.jpg',2];
        $sql = "insert into invitations (invitation_id,name,mobile,filename,booking_id)values(?,?,?,?,?)";
        $statement = $conn->prepare($sql);
        $success = $statement->execute($values);
        if ($success) {
            echo"Insert invitations record successed!";
        } else {
            echo"Insert invitations record failed!";
        }
        echo '<br>';
        //Insert users
        $values = [3,  'Smith', '[email protected]', 'password'];
        $sql = "insert into users (user_id,username,email,password)values(?,?,?,?)";
        $statement = $conn->prepare($sql);
        $success = $statement->execute($values);
        if ($success) {
            echo"Insert users record successed!";
        } else {
            echo"Insert users record failed!";
        }
        echo '<br>';
        ?>
    </body>
</html>

Lab9.3 - Update Records using PDO

更新数据库数据

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        //Update booking
        $booking_id = 1;
        $values = ['Kim', 'Kardashian', '[email protected]', '12:30:00', '1/10/2019', 20000];
        $dsn = 'mysql:host=localhost;dbname=ebookingsdb';
        $username = 'root';
        $password = '';
        $conn = new PDO($dsn, $username, $password);
        $sql = "update bookings set first_name = ?,last_name = ?,email = ?,booking_date = ?,booking_time = ?,num_people = ? where booking_id = $booking_id";
        $statement = $conn->prepare($sql);
        $success = $statement->execute($values);
        if ($success) {
            echo "Update booking record successed!";
        } else {
            echo "Update booking record failed!";
        }
        echo "<br>";

        //Update invitations
        $invitation_id = 1;
        $values = ['whh', '457412356', 'lll.jpg'];
        $sql = "update invitations set name = ?,mobile = ?,filename = ?where invitation_id = $invitation_id";
        $statement = $conn->prepare($sql);
        $success = $statement->execute($values);
        if ($success) {
            echo "Update invitations record successed!";
        } else {
            echo "Update invitations record failed!";
        }
        echo "<br>";

        //Update users
        $user_id = 1;
        $values = ['whh', '[email protected]', '1111'];
        $sql = "update users set username = ?,email = ?,password = ?where user_id = $user_id";
        $statement = $conn->prepare($sql);
        $success = $statement->execute($values);
        if ($success) {
            echo "Update users record successed!";
        } else {
            echo "Update users record failed!";
        }
        echo "<br>";
        ?>
    </body>
</html>

Lab9.4 - Delete Records using PDO

删除数据库数据

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        //Delete something in booking 
        $dsn = 'mysql:host=localhost;dbname=ebookingsdb';
        $username = 'root';
        $password = '';
        $conn = new PDO($dsn, $username, $password);
        $booking_id = 8;
        $sql = "delete from bookings where booking_id = $booking_id";
        $statement = $conn->query($sql);
        $success = $statement->execute();
        if ($success) {
            echo "Delete booking record successed!";
        } else {
            echo "Delete booking record failed!";
        }
        echo "<br>";
        
        // delete any related records in the Invitations table that belong to the booking record deleted.   
        $sql = "delete from invitations where booking_id = $booking_id";
        $statement = $conn->query($sql);
        $success = $statement->execute();
        if ($success) {
            echo "Delete invitations record successed!";
        } else {
            echo "Delete invitations record failed!";
        }
        echo "<br>";
        ?>
    </body>
</html>

Lab9.5 - Search Records using PDO

查询数据库数据

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        //seach Smith in bookings
        $conn = mysqli_connect('localhost', 'root', '', 'ebookingsdb'); 
        $keyword = "Smith";
        $res = mysqli_query($conn, "select * from bookings where first_name like '%$keyword%' or last_name like '%$keyword%' or email like '%$keyword%' or booking_date like '%$keyword%' or booking_time like '%$keyword%' or num_people like '%$keyword%'") or die(mysqli_error($conn));
        while ($row = mysqli_fetch_assoc($res)) {
            foreach ($row as $key => $value) {
                echo "$key : $value <br/>";
            }
        }
        echo "<hr>";
        //seach mouse in  invitations 
        $conn = mysqli_connect('localhost', 'root', '', 'ebookingsdb'); 
        $keyword = "Mouse";
        $res = mysqli_query($conn, "select * from invitations where name like '%$keyword%' or filename like '%$keyword%' ") or die(mysqli_error($conn));
        while ($row = mysqli_fetch_assoc($res)) {
            foreach ($row as $key => $value) {
                echo "$key : $value <br/>";
            }
        }
        ?>
    </body>
</html>

Lab9.6 - Progress Activity

综合练习:
实现查询和添加功能
在这里插入图片描述

以table的形式输出数据库中的内容:
在这里插入图片描述
以form的形式往数据库里插入数据:

在这里插入图片描述
文件结构:
在这里插入图片描述
index.php:

<?php

function validateDate($date) {
            $valid = false;
            if (preg_match("/\d{2}\/\d{2}\/\d{4}/", $date)) {
                // if we are here user has entered format of dd/mm/yyyy
                $day = $month = $year = "";
                // split up the pieces 
                list($day, $month, $year) = explode("/", $date);

                $day = intval($day);
                $month = intval($month);
                $year = intval($year);

                // now use PHP checkdate to verify it is a valid date 
                if (checkdate($month, $day, $year)) {
                    $valid = true;
                }
            }
            return $valid;
        }

function reformat($string) {
    $day = $month = $year = $result = "";
    if (preg_match("/\d{2}\/\d{2}\/\d{4}/", $string)) {
        list($day, $month, $year) = explode("/", $string);
        $result = $year . "-" . $month . "-" . $day;
    }
    return $result;
}

include_once('includes/header.php');
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    if ($action == 'viewBookings') {
        //read records code here
        $conn = new PDO("mysql:host=localhost;dbname=ebookingsdb;charset=utf8", "root", "");
        $statement = $conn->query("select * from bookings order by booking_id");
        $statement->setFetchMode(PDO::FETCH_ASSOC);
        $records = [];
        while ($row = $statement->fetch()) {
            $records[] = $row;
        }
        //display records in bootstrap table
        include_once("includes/viewBookings.php");
    } else if ($action == 'addBooking') {

        $first_name = '';
        $last_name = '';
        $email = '';
        $booking_date = '';
        $booking_time = '';
        $num_people = '';
        $errors = [];
        if (isset($_POST['submit'])) {
            //validation
            if (isset($_POST['first_name'])) {//设定first_name的输入规范
                $first_name = $_POST['first_name'];
                if (strlen($first_name) == 0) {
                    $errors['first_name'] = 'First Name is missing input';
                } elseif (!ctype_alpha($first_name)) {
                    $errors['first_name'] = 'Enter a valid First Name';
                }
            }

            if (isset($_POST['last_name'])) {//设定last_name的输入规范
                $last_name = $_POST['last_name'];
                if (strlen($last_name) == 0) {
                    $errors['last_name'] = 'Last Name is missing input';
                } elseif (!ctype_alpha($last_name)) {
                    $errors['last_name'] = 'Enter a valid Last Name';
                }
            }

            if (isset($_POST['email'])) {//设定email的输入规范
                $email = trim($_POST['email']);
                if (strlen($email) == 0) {
                    $errors['email'] = "Email address is missing input";
                } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $errors['email'] = "Enter a valid Email Address";
                }
            }

            if (isset($_POST['booking_date'])) {
                $temp = $_POST['booking_date'];
                $booking_date = reformat($_POST['booking_date']);
                if ($temp == "dd/mm/yyyy") {
                    $errors['booking_date'] = 'Booking date is missing input';
                } elseif (!validateDate($temp)) {
                    $errors['booking_date'] = 'Booking date is not valid';
                }
            }

            if (isset($_POST['booking_time'])) {
                $booking_time = $_POST['booking_time'];
                if (strlen($booking_time) == 0) {
                    $errors['booking_time'] = 'booking_time is missing input';
                }
            }

            if (isset($_POST['num_people'])) {
                $num_people = $_POST['num_people'];
                if (strlen($num_people) == 0) {
                    $errors['num_people'] = 'Number of people is missing input';
                }
            }

            if (count($errors) == 0) {
                //insert booking record code here
                $values = [$first_name, $last_name, $email, $booking_date, $booking_time, $num_people];
                $dsn = 'mysql:host=localhost;dbname=ebookingsdb';
                $username = 'root';
                $password = '';
                $conn = new PDO($dsn, $username, $password);
                $sql = "insert into bookings (first_name,last_name,email,booking_date,booking_time,num_people)values(?,?,?,?,?,?)";
                $statement = $conn->prepare($sql);
                $success = $statement->execute($values);
                if ($success) {
                    include_once 'index.php'; //如果无错误就返回主页
                    echo"Insert booking record successed!";
                } else {
                    include_once 'index.php';
                    echo"Insert booking record failed!";
                }
            } else {
                include_once 'includes/addBookingForm.php'; //有不符合规范的就返回form并提示
            }
        } else {
            include_once 'includes/addBookingForm.php';
        }
    } else {
        include_once('includes/content.php');
    }
}
include_once('includes/footer.php');

viewBookings.php:

<br>
<br>
<div class="container">
    <div class="row">
        <div class="col-md-3 text-center"></div>
        <div class="col-md-6 box text-center">View Bookings:<?= count($records) ?>results</div>
        <div class="col-md-3 text-center"></div>
    </div>
    <div class="row">
        <div class="col-md-3 text-center"></div>
        <div class="col-md-6 jumbotron text-center">
            <table class="table table-striped table-hover" >
                <tr class="info">
                    <th>Booking ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Booking Date</th><th>Booking Time</th><th>People</th><th>Manage</th>
                </tr>
                <?php foreach ($records as $row): ?>
                    <tr>
                        <td align="left"><?= $row['booking_id'] ?></td> 
                        <td align="left"><?= $row['first_name'] ?></td>
                        <td align="left"><?= $row['last_name'] ?></td> 
                        <td align="left"><?= $row['email'] ?></td> 
                        <td align="left"><?= $row['booking_date'] ?></td> 
                        <td align="left"><?= $row['booking_time'] ?></td> 
                        <td align="left"><?= $row['num_people'] ?></td> 
                        <td align="left">
                            <a href="?action=editBooking&booking_id=<?= $row['booking_id'] ?>" >Edit</a> 
                            &nbsp;
                            <a href="?action=deleteBooking&booking_id=<?= $row['booking_id'] ?>" >Delete</a> 
                        </td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>
        <div class="col-md-3 text-center"></div>
    </div>
</div>

addBookingForm.php:

<div class="container">

    <div class="row">
        <div class="col-sm-3"></div>
        <div class="col-sm-6 box text-center">
            Add Booking
        </div>
        <div class="col-sm-3"></div>
    </div>

    <div class="row">
        <div class="col-sm-3"></div>
        <div class="col-sm-6 jumbotron">
            <form action="" method="post" novalidate="true">
                <div class="form-group">
                    <label class="control-label">
                        First Name
                        <span class="error" style="color:red">
                            <?= isset($errors['first_name']) ? $errors['first_name'] : "" ?>
                        </span>
                    </label>
                    <input class="form-control" type="text" name="first_name"maxlength="30" value="<?= $first_name ?>" />
                </div>

                <div class="form-group">
                    <label class="control-label">
                        Last Name
                    </label>
                    <span class="error" style="color:red">
                        <?= isset($errors['last_name']) ? $errors['last_name'] : "" ?>
                    </span>
                    <input class="form-control" type="text" name="last_name"maxlength="30" value="<?= $last_name ?>" />
                </div>    
                
                <div class="form-group">
                    <label class="control-label">
                        Email
                    </label>
                    <span class="error" style="color:red">
                        <?= isset($errors['email']) ? $errors['email'] : "" ?>
                    </span>
                    <input class="form-control" type="email" name="email" value="<?= $email ?>"/>
                </div>  

                <div class="form-group">
                    <label class="control-label">
                        Booking Date
                    </label>
                    <span class="error" style="color:red">
                        <?= isset($errors['booking_date']) ? $errors['booking_date'] : "" ?>
                    </span>
                    <input class="form-control" type="date" name="booking_date"value="dd/mm/yyyy" />
                </div>

                <div class="form-group">
                    <label class="control-label">
                        Booking Time
                    </label>
                    <span class="error" style="color:red">
                        <?= isset($errors['booking_time']) ? $errors['booking_time'] : "" ?>
                    </span>
                    <input class="form-control" type="time" name="booking_time" value="<?= $booking_time ?>"/> 
                </div>

                <div class="form-group">
                    <label class="control-label">
                        Number of People
                    </label>
                    <span class="error" style="color:red">
                        <?= isset($errors['num_people']) ? $errors['num_people'] : "" ?>
                    </span>
                    <input class="form-control" type="text" name="num_people" value="<?= $num_people ?>"/>
                </div>
                <br/>
                <div class="form-group">

                    <input class="btn btn-primary btn-block" type="submit" name="submit" />
                </div>  
            </form>
        </div>
        <div class="col-sm-3"></div>
    </div>



原创文章 85 获赞 46 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Deam_swan_goose/article/details/105622125
今日推荐