在本教程中,我们将学习如何使用PDO API将数据插入到数据库表中。
以下是如何使用PDO将数据插入表的步骤:
我们将在示例数据库empdb中的departments表中插入一个新部门。
创建部门
我们将把以下代码放在脚本文件的开头:
<?php
$msg
=
''
;
$result
= false;
if
(isset(
$_POST
[
'submit'
])) {
require_once
'dbconfig.php'
$dsn
"mysql:host=$host;dbname=$db"
try
{
// 建立数据库连接
$dbh
new
PDO(
,
$username
$password
);
// 创建新的部门
= create_dept();
// 再次显示插入表单
display_form();
}
catch
(PDOException
$e
) {
echo
->getMessage();
else
// display insert form
如果表单没有提交,我们将显示它。如果它被提交,我们执行上面描述的逻辑。
以下是每一步的函数:
函数-验证部门:
/**
* 验证部门
* @return boolean 成功时返回部门名称,失败时返回false
*/
function
validate_dept() {
global
$dept_name
'department'
];
(
!=
= filter_var(
, FILTER_SANITIZE_STRING);
return
'请输入部门名称'
false;
函数-检查部门是否存在
* 检查部门是否存在
* @param string $dept_name 部门名称
* @return NULL|boolean 如果部门存在,返回true;如果不存在,返回false;如果失败,返回NULL
dept_exist(
$sql_select
= "SELECT department_no
FROM departments
WHERE name =
" . $dbh->quote($dept_name) . "
LIMIT 1";
$stmt
->query(
=== false) {
'查询部门表departments出错'
NULL;
$r
->fetch(PDO::FETCH_ASSOC);
!== false) {
"名称叫 $dept_name 的部门已存在."
true;
函数 - 表中添加一个新部门
* 表中添加一个新的部门
* @return boolean 成功时返回true,失败时返回false
insert_dept(
// 构造SQL insert语句
$sql_insert
= "INSERT INTO departments(name)
VALUES(
)";
->
exec
) === false) {
'添加新部门错误。'
"新部门 $dept_name 已添加"
函数 - 创建新部门,包括验证逻辑,检查是否已存在和创建
* 添加新部门
create_dept() {
// 验证部门值
= validate_dept();
// 检查部门是否已存在
(!dept_exist(
)) {
// 数据表中添加部门
函数 - 显示错误或成功消息
* 根据消息类型显示消息
* @param string $msg 要显示的消息
* @param boolean $type true: 成功的消息,
* false: 失败的消息
display_msg(
$type
=== true ?
$cssClass
"alert-success"
:
"alert-error"
?>
<div
class
"alert <?php echo $cssClass; ?>"
>
; ?>
</div>
函数 - 显示表单
* 显示创建新部门的表单
display_form() {
<!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>
"container"
style=
"margin-top:20px;"
<form action =
"<?php $_SERVER['PHP_SELF'] ?>"
method =
"POST"
"form-horizontal"
<?php display_msg(
); ?>
"control-group"
<label
for
"department"
"control-label"
>部门:</label>
"controls"
<input type=
"text"
name=
id=
"input-xlarge"
placeholder=
"输入部门名称"
/>
<input name=
"submit"
type=
value=
"创建部门"
"btn btn-primary"
</form>
</body>
</html>
原文链接:https://codingdict.com/