html表单提交数据保存到mysql中_php – Canonical:如何将HTML表单数据保存到MySQL数据库中...
首先,您的PHP或HTML页面应该生成一个用户可以与之交互的表单.最多简单的形式它是这样的:这将为您的用户提供一个简单的表单,其中包含单个输入字段和“保存”按钮.点击后内容的“保存”按钮将使用POST方法发送到您的“yourscript.php”.yourscript.php应该实现以下内容:>接受并处理表单中的输入.>连接到MySQL数据库.>存储到数据库中.以最简单的形式,这
首先,您的PHP或HTML页面应该生成一个用户可以与之交互的表单.最多
简单的形式它是这样的:
这将为您的用户提供一个简单的表单,其中包含单个输入字段和“保存”按钮.点击后
内容的“保存”按钮将使用POST方法发送到您的“yourscript.php”.
yourscript.php应该实现以下内容:
>接受并处理表单中的输入.
>连接到MySQL数据库.
>存储到数据库中.
以最简单的形式,这将是:
Process and store// Check that user sent some data to begin with.
if (isset($_REQUEST['yourfield'])) {
/* Sanitize input. Trust *nothing* sent by the client.
* When possible use whitelisting, only allow characters that you know
* are needed. If username must contain only alphanumeric characters,
* without puntation, then you should not accept anything else.
* For more details, see: https://stackoverflow.com/a/10094315
*/
$yourfield=preg_replace('/[^a-zA-Z0-9\ ]/','',$_REQUEST['yourfield']);
/* Escape your input: use htmlspecialchars to avoid most obvious XSS attacks.
* Note: Your application may still be vulnerable to XSS if you use $yourfield
* in an attribute without proper quoting.
* For more details, see: https://stackoverflow.com/a/130323
*/
$yourfield=htmlspecialchars($yourfield);
} else {
die('User did not send any data to be saved!');
}
// Define MySQL connection and credentials
$pdo_dsn='mysql:dbname=yourdatabase;host=databasehost.example.com';
$pdo_user='yourdatabaseuser';
$pdo_password='yourdatabaspassword';
try {
// Establish connection to database
$conn = new PDO($pdo_dsn, $pdo_user, $pdo_password);
// Throw exceptions in case of error.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Use prepared statements to mitigate SQL injection attacks.
// See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php for more details
$qry=$conn->prepare('INSERT INTO yourtable (yourcolumn) VALUES (:yourvalue)');
// Execute the prepared statement using user supplied data.
$qry->execute(Array(":yourvalue" => $yourfield));
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage() . " file: " . $e->getFile() . " line: " . $e->getLine();
exit;
}
?>
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)