[英]submit html form using php but stay on same page
I have a simple HTML form, for example:我有一个简单的 HTML 表格,例如:
<form action="insert.php" method="post">
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
<input type="submit" value="Submit">
using a PHP script I called insert.php:使用我称为 insert.php 的 PHP 脚本:
$sql = "INSERT INTO database VALUES ('$firstName','$lastName)";
if(mysqli_query($Conn,$sql)){
echo "<h3>data stored in database successfully.</h3>";
} else{
echo mysqli_error($Conn);
}
I add the input from the form to a SQL database.我将表单中的输入添加到 SQL 数据库中。 Obviously, after the submit button is pressed, the browser ends up on insert.php with the success message printed(action="insert.php").
显然,在按下提交按钮后,浏览器会在 insert.php 上结束,并打印成功消息(action="insert.php")。 I want to know how can I keep the browser on the form page and print the success/error message somewhere on the same page.
我想知道如何将浏览器保留在表单页面上并在同一页面的某处打印成功/错误消息。
Either use Ajax to do the submission, or have your insert.php code in your main script - change your form to submit to the same page it appears on by simply removing the action=""
attribute.要么使用 Ajax 进行提交,要么在主脚本中使用 insert.php 代码 - 只需删除
action=""
属性,即可将表单更改为提交到它出现的同一页面。
Check if the form has been submitted - eg by looking for the submit button having been pressed in the $_REQUEST
or $_POST
arrays, then do the insert.检查表单是否已提交 - 例如通过查找在
$_REQUEST
或$_POST
arrays 中按下的提交按钮,然后执行插入。
Or a third option - in your insert.php redirect the user back to where they came from after processing.或者第三个选项 - 在您的 insert.php 中,在处理后将用户重定向回他们来自的位置。
Have a read up on why you shouldn't write user-submitted data straight to your database - and consider using mysqli_real_escape_string or parameterised queries.仔细阅读为什么不应该将用户提交的数据直接写入数据库 - 并考虑使用 mysqli_real_escape_string 或参数化查询。
You can record the message in one session and show the message after redirecting to the previous page.您可以将消息记录在一个 session 中,并在重定向到上一页后显示该消息。
start_session();
public function message($msg = ""){
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} elseif (isset($_SESSION['message'])) {
// then this is "get message"
$this->message = $_SESSION['message'];
return $this->message;
}
}
function redirect_to($new_link){
header("Location: " . $new_link);
exit;
}
if ($Variable->create()) {
$session->message("New user created...");
redirect_to("URL");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.