我将插入表单的数据插入到数据库表中。这里使用POST方法通知我将数据发送到PDO的后台功能。表单是前端Bootstrap表单,PDO是后端。但是代码无效,请帮帮我。
表单代码: 这是Form表的Bootstrap代码,它是前端。
<div class="col-lg-6">
<div class="card alert">
<div class="card-header">
<h4>Horizontal Form</h4>
</div>
<div class="card-body">
<div class="horizontal-form">
<form method="post" action="channel.php" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input style="color:white" name="name" type="text" class="form-control" placeholder="Channel Name" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<input style="color:white" name="desp" type="text" class="form-control" placeholder="Channel Description" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Field 1</label>
<div class="col-sm-10">
<input style="color:white" name="f1" type="text" class="form-control" placeholder="Field 1" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Field 2</label>
<div class="col-sm-10">
<input style="color:white" name="f2" type="text" class="form-control" placeholder="Field 2">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Field 3</label>
<div class="col-sm-10">
<input style="color:white" name="f3" type="text" class="form-control" placeholder="Field 3">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Field 4</label>
<div class="col-sm-10">
<input style="color:white" name="f4" type="text" class="form-control" placeholder="Field 4">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Create Channel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
PDO功能
public function create_channel($name,$desp,$f1,$f2,$f3,$f4)
{
try {
$db = DB();
$query = $db->prepare("INSERT INTO sensor_table(table_name, table_desp, field_1, field_2, field_3, field_4) VALUES (:name,:desp,:fl1,:fl2,:fl3,:fl4)");
$query->bindParam("name", $name, PDO::PARAM_STR);
$query->bindParam("desp", $desp, PDO::PARAM_STR);
$query->bindParam("fl1", $f1, PDO::PARAM_STR);
$query->bindParam("fl2", $f2, PDO::PARAM_STR);
$query->bindParam("fl3", $f3, PDO::PARAM_STR);
$query->bindParam("fl4", $f4, PDO::PARAM_STR);
$query->execute()
return $db->lastInsertId();
} catch (PDOException $e) {
header("Location: login.php");
exit($e->getMessage());
}
}
数据库连接代码:
define('HOST', 'localhost');
define('USER', 'root');
define('PASSWORD', '');
define('DATABASE', 'elg_iot');
function DB()
{
try {
$db = new PDO('mysql:host='.HOST.';dbname='.DATABASE.'', USER, PASSWORD);
return $db;
} catch (PDOException $e) {
return "Error!: " . $e->getMessage();
die();
}
}