真正优秀的程序员是那些专注于认识、理解、沟通和解决问题的人,你得明白,软件只是用来增加效率的工具而已

PDO预处理实现表单的提交功能

1.创建表结构

DROP TABLE IF EXISTS `message`;
CREATE TABLE `message` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(64) NOT NULL DEFAULT '',
  `content` varchar(64) NOT NULL DEFAULT '',
  `created_at` int(10) unsigned NOT NULL DEFAULT '0',
  `user_name` varchar(64) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.表单页面 form.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>111</title>
    </head>
    <body>
        <div class="main">
            <form action="form.php" method="post">
                标题:
                <input type="text" name="title"> <br>
                内容:
                <textarea name="content" cols="10" rows="5" ></textarea><br>
                用户:
                <input type="text" name="user_name"><br>
                <button type="sumit">提交</button>
            </form>
        </div>
    </body>

</html>

3.提交数据页面 form.php

<?php

$title   = $_POST['title'];
$content = $_POST['content'];
$user_name = $_POST['user_name'];

if(empty($title) || empty($content) || empty($user_name)){
    exit('请传入有效的参数');
}

try {
    $dsn      = 'mysql:dbname=test;host=localhost';
    $userName = 'root';
    $password = 'root';

    $pdo = new PDO($dsn,$userName,$password);

    $sql = 'insert into message(title,content,created_at,user_name) values(:title,:content,:created_at,:user_name)';

    $stmt = $pdo->prepare($sql);

    $data = [
        ':title' => $title,
        ':content' => $content,
        ':created_at' => time(),
        ':user_name' => $user_name
    ];

    $stmt->execute($data);
    $rows = $stmt->rowCount();

    if($rows){
        exit('添加成功');
    }else{
        exit('添加失败');
    }

} catch(PDOException $e){
    echo $e->getMessage();
}

微风小站 » PDO预处理实现表单的提交功能
分享到: 更多 (0)