PDO将数据插入表中


在本教程中,我们将学习如何使用PDO API将数据插入到数据库表中。

以下是如何使用PDO将数据插入表的步骤:

  • 通过创建一个新的PDO对象来创建到数据库的连接。
  • 使用SQL INSERT语句将数据插入到表中。
  • 调用PDO对象的exec()方法来执行INSERT语句。exec()方法返回成功时受影响的行数,失败时返回false。
  • </ul> </div>

    PDO将数据插入到表中 - 示例

    我们将在示例数据库empdb中的departments表中插入一个新部门。

    1. 首先,我们创建一个用于创建新部门的表单。
      表单由一个接受部门名称的文本字段和一个提交按钮组成。
    2. </ol>

      1. 然后,当我们输入部门名称并点击创建部门按钮时,我们需要:
      2. </ol>

        • 使用filter_var()函数校验用户的输入
        • 通过查询部门表的数据,检查输入部门名称是否已经存在。如果部门已经存在,则显示一条错误消息。否则,我们将插入新部门并显示一条成功消息。
        • </ul>

          1. 要将一个新部门插入到departments表中,我们需要构造一个insert语句并调用PDO对象的exec()方法。
          2. </ol>

            将数据插入表脚本

            我们将把以下代码放在脚本文件的开头:

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            <?php
            $msg = '';
            $result = false;
            if (isset($_POST['submit'])) {
            require_once 'dbconfig.php';
            $dsn = "mysql:host=$host;dbname=$db";
            try {
            // 建立数据库连接
            $dbh = new PDO($dsn, $username, $password);
            // 创建新的部门
            $result = create_dept();
            // 再次显示插入表单
            display_form();
            } catch (PDOException $e) {
            echo $e->getMessage();
            }
            } else {
            // display insert form
            display_form();
            }

            如果表单没有提交,我们将显示它。如果它被提交,我们执行上面描述的逻辑。

            以下是每一步的函数:

            函数-验证部门:

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            /**
            * 验证部门
            * @return boolean 成功时返回部门名称,失败时返回false
            */
            function validate_dept() {
            global $msg;
            $dept_name = $_POST['department'];
            if ($dept_name != '') {
            $dept_name = filter_var($dept_name, FILTER_SANITIZE_STRING);
            return $dept_name;
            } else {
            $msg = '请输入部门名称';
            return false;
            }
            }

            函数-检查部门是否存在

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            /**
            * 检查部门是否存在
            * @param string $dept_name 部门名称
            * @return NULL|boolean 如果部门存在,返回true;如果不存在,返回false;如果失败,返回NULL
            */
            function dept_exist($dept_name) {
            global $msg, $dbh;
            $sql_select = "SELECT department_no
            FROM departments
            WHERE name = " . $dbh->quote($dept_name) . "
            LIMIT 1";
            $stmt = $dbh->query($sql_select);
            if ($stmt === false) {
            $msg = '查询部门表departments出错';
            return NULL;
            }
            $r = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($r !== false) {
            $msg = "名称叫 $dept_name 的部门已存在.";
            return true;
            } else
            return false;
            }

            函数 - 表中添加一个新部门

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            /**
            * 表中添加一个新的部门
            * @param string $dept_name 部门名称
            * @return boolean 成功时返回true,失败时返回false
            */
            function insert_dept($dept_name) {
            global $dbh, $msg;
            // 构造SQL insert语句
            $sql_insert = "INSERT INTO departments(name)
            VALUES(" . $dbh->quote($dept_name) . ")";
            if ($dbh->exec($sql_insert) === false) {
            $msg = '添加新部门错误。';
            return false;
            } else {
            $msg = "新部门 $dept_name 已添加";
            return true;
            }
            }

            函数 - 创建新部门,包括验证逻辑,检查是否已存在和创建

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            /**
            * 添加新部门
            * @return boolean 成功时返回true,失败时返回false
            */
            function create_dept() {
            // 验证部门值
            $dept_name = validate_dept();
            if ($dept_name) {
            // 检查部门是否已存在
            if (!dept_exist($dept_name)) {
            // 数据表中添加部门
            return insert_dept($dept_name);
            }
            }
            return false;
            }

            函数 - 显示错误或成功消息

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            /**
            * 根据消息类型显示消息
            * @param string $msg 要显示的消息
            * @param boolean $type true: 成功的消息,
            * false: 失败的消息
            */
            function display_msg($msg, $type) {
            $type === true ? $cssClass = "alert-success" :
            $cssClass = "alert-error";
            if ($msg != '') {
            ?>
            <div class="alert <?php echo $cssClass; ?>">
            <?php echo $msg; ?>
            </div>
            <?php
            }
            }

            函数 - 显示表单

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            <?php
            /**
            * 显示创建新部门的表单
            */
            function display_form() {
            global $msg, $result;
            ?>
            <!DOCTYPE html>
            <html>
            <head>
            <title>创建部门</title>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css">
            </head>
            <body>
            <div class="container" style="margin-top:20px;">
            <form action = "<?php $_SERVER['PHP_SELF'] ?>"
            method = "POST"
            class = "form-horizontal">
            <?php display_msg($msg, $result); ?>
            <div class="control-group">
            <label for="department" class="control-label">部门:</label>
            <div class="controls">
            <input type="text"
            name="department"
            id="department"
            class="input-xlarge"
            placeholder="输入部门名称" />
            </div>
            </div>
            <div class="control-group">
            <div class="controls">
            <input name="submit"
            type="submit"
            value="创建部门"
            class="btn btn-primary" />
            </div>
            </div>
            </form>
            </div>
            </body>
            </html>
            <?php
            }


            原文链接:https://codingdict.com/