[英]How to Insert an entry to MySQL DB from HTML Form
所以,我的页面中有一个带有某些字段的表单。 例如 - auth.php。 通过调用一些 php 函数接收此表单字段中的数据,该函数从 MySQL DB 提供此数据。 编码:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
通过此代码在字段中插入的数据:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
但是如何实现向我的 MySQL 数据库插入一些条目的机制。 例如,用户按下我的表单上的添加按钮,用他自己的数据填充字段“名称”并按下保存按钮 - 我想直接将此用户数据保存在我的 MySQL 数据库中。
请帮忙!
为此,您需要执行以下几个步骤:
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
现在您应该能够将数据保存在数据库中。
请看一下这个例子,了解如何连接到数据库http://docs.kisphp.net/database-connect/
您可以/应该使用 PDO 而不是 mysqli。
在您的代码中:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
遵循一些原则始终是一个好习惯:
?>
等等。 你可以在这里找到更多细节http://www.php-fig.org/psr/psr-2/
这是基本用法。 一旦理解了原理,就可以将其扩展到ajax。 创建一个将表单数据提交到submit.php
文件的 ajax 函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.