【发布时间】:2017-02-18 01:08:49
【问题描述】:
我有一个 WordPress 网站,想创建一个表单(输入 → 数据库)。
我看过两个教程:
- How you can easily create customized form in WordPress
- How to create custom forms in WordPress without using plugins?
它们都非常相似。使用 HTML 和 JavaScript 创建前端,然后使用 PHP 处理信息到数据库。
我的问题是,每当我提交表单时,它都会显示一个 404 页面,上面写着:
哎呀!找不到该页面。
现在我的问题是(或者我想知道):
-
我需要将
process.php文件放在哪里? (我正在使用FileZilla)。我尝试了public_html/wp-content文件夹中的几个地方。 -
为什么不验证姓名和电子邮件字段? (对于空名称字段等没有警报)
表格结构:
您的姓名:[TEXT],您的电子邮件:[TEXT],性别:[*男 *女],您的年龄:[TEXT],[提交按钮]
表单页面:
<form name="myForm" method="POST" onsubmit="return form_validation()" action="../process.php">
Your Name: <input id="customer_name" name="customer_name" type="text" />
Your Email: <input id="customer_email" name="customer_email" type="text" />
Sex: <input name="customer_sex" type="radio" value="male" />Male <input name="customer_sex" type="radio" value="female" />Female
Your Age: <input id="customer_age" name="customer_age" type="text" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function form_validation() {
/* Check the Customer Name for blank submission */
var customer_name = document.forms["myForm"]["customer_name"].value;
if (customer_name == "" || customer_name == null) {
alert("Name field must be filled.");
return false;
}
/* Check the Customer Email for invalid format */
var customer_email = document.forms["myForm"]["customer_email"].value;
var at_position = customer_email.indexOf("@");
var dot_position = customer_email.lastIndexOf(".");
if (at_position < 1 || dot_position < at_position + 2 || dot_position + 2 >= customer_email.length) {
alert("Given email address is not valid.");
return false;
}
}
</script>
文件process.php(未编辑):
<?php
$customer_name = $_POST["customer_name"];
$customer_email = $_POST["customer_email"];
$customer_sex = $_POST["customer_sex"];
$customer_age = $_POST["customer_age"];
$conn = mysqli_connect("Database Host", "Database Username", "Database Password", "Database Name");
if(!$conn) {
die(‘Problem in database connection: ‘ . mysql_error());
}
$query = "INSERT INTO ‘Database Name’.’Table Name’ ( ‘customer_name’, ‘customer_email’, ‘customer_sex’, ‘customer_age’ ) VALUES ( $customer_name, $customer_email, $customer_sex, $customer_age )";
mysqli_query($conn, $query);
header("Location: my-site.com/success"); // Redirects to success page
?>
【问题讨论】:
-
当您将自己的功能添加到 WordPress 网站时,最好创建一个插件。
-
您可以创建自己的插件,也可以搜索一些完全符合您要求的免费插件。当然,那里有很多……只是做一些搜索
-
你可以使用 pods.io 框架,这将让你创建任何你想要创建的东西
-
这个答案很好地说明了这个问题的答案,但仅供所有创建自定义 WordPress 表单的开发人员参考,不要在 MySQL 查询中使用直接 POST 字段插入。绝不。这可能导致严重的SQL injection hacks。也不要完全依赖于客户端验证。任何人都可以直接对 PHP 服务器本身执行denial-of-service attack。故事的寓意是始终进行服务器端验证!
-
@Michael Plautz:什么答案? M. Abdulai's here?还是其他答案?或者在这里发表评论?还是别的什么?