Я пытаюсь создать контактную форму, чтобы люди могли оставлять сообщения на веб-сайте. По сути, я хочу, чтобы это был процесс с одной страницей с успехом или сообщение об ошибке на той же странице. Тем не менее, я новичок в PHP, поэтому я не уверен, куда идти, откуда я сейчас застрял.Как создать одностраничную форму PHP-формы
До сих пор я получил форму для отправки, но всегда возвращается с отсутствующими полями, даже если поля отсутствуют. Также страница перезагружается и возвращается в начало страницы. Есть ли способ после подачи формы, чтобы он не возвращался в начало страницы после отправки формы?
Вот HTML-форма, по существу, это веб-сайт с одной страницей, разделенный на разные слайды. После отправки формы я хочу, чтобы страница оставалась на слайде4, где будет форма и сообщение об ошибке/ошибке.
<div id="slide4">
<div class="slidetitle">Contact Me</div>
<div class="content">
<form action="index.php" method="POST" id="contactform" target="_self">
<input type="hidden" name="postid" value="<?php $postid?>">
<table>
<tr><td><b>First Name:</b></td><td><input type="text" name="firstName" size="45" value="<?php $firstName?>"></td></tr>
<tr><td><b>Last Name:</b></td><td><input type="text" name="lastName" size="45" value="<?php $lastName?>"></td></tr>
<tr><td><b>Email:</b></td><td><input type="email" name="email" size="45" value="<?$email?>"></td></tr>
<tr><td><b>Phone:</b></td><td><input type="tel" name="phone" size="45" value="<?$phone?>"></td></tr>
<tr><td><b>Content:</b></td><td><textarea name="content" form="contactform" rows="10" cols="100"><?php echo $content; if (empty($content)){ echo "Enter text here...";} ?></textarea></td></tr>
<tr><td colspan=2 style="text-align: center"><input type=submit name="submit1" value="Leave me a message"></td></tr>
</table>
</form>
<div id="contactoutput">
<?php $output ?>
</div>
</div>
</div>
И вот обновленный PHP для формы после реализации изменений, которые предложил Фрэнк.
<?php
$firstName = "";
$lastName= "";
$email = "";
$phone = "";
$content = "";
$errMsg = "";
?>
<?php $errMsg ?>
<?php
if (isset($_POST['submit1'])) {
// ==========================
//validate user input
// set up the required array
$required = array("firstName","lastName","email","phone","content"); // note that, in this array, the spelling of each item should match the form field names
// set up the expected array
$expected = array("firstName","lastName", "email","phone","content","postid"); // again, the spelling of each item should match the form field names
$missing = array();
foreach ($expected as $field){
// isset($_POST[$field]): Note that if there is no user selection for radio buttons, checkboxes, selection list, then $_POST[$field] will not be set
// Under what conditions the script needs to record a field as missing -- $field is required and one of the following two (1) $_POST[$field] is not set or (2) $_POST[$field] is empty
//echo "$field: in_array(): ".in_array($field, $required)." empty(_POST[$field]): ".empty($_POST[$field])."<br>";
if (in_array($field, $required) && (!isset($_POST[$field]) || empty($_POST[$field]))) {
array_push ($missing, $field);
} else {
// Passed the required field test, set up a variable to carry the user input.
// Note the variable set up here uses a variable name as the $field value. In this example, the first $field in the foreach loop is "title" and a $title variable will be set up with the value of "" or $_POST["title"]
if (!isset($_POST[$field])) {
//$_POST[$field] is not set, set the value as ""
${$field} = "";
} else {
${$field} = $_POST[$field];
}
}
}
//print_r ($missing); // for debugging purpose
/* add more data validation here */
// ex. $price should be a number
/* proceed only if there is no required fields missing and all other data validation rules are satisfied */
$stmt = $conn->stmt_init();
$sql = "Insert Into msg_table16 (firstName, lastName, email, content, phone, postid) values (?, ?, ?, ?, ?, ?)";
if($stmt->prepare($sql)){
// Note: user input could be an array, the code to deal with array values should be added before the bind_param statement.
$stmt->bind_param('ssssii',$firstName, $lastName,$email,$content,$phone,$postid);
$stmt_prepared = 1; // set up a variable to signal that the query statement is successfully prepared.
}
if ($stmt_prepared == 1){
if ($stmt->execute()){
$output = "<p>The following information has been saved in the database:<br><br>";
foreach($_POST as $key=>$value){
$output .= "<b>$key</b>: $value <br>"; //$key (form field names) may not be very indicative (ex. lname for the last name field), you can set up the form field names in a way that can be easily processed to produce more understandable message. (ex. use field names like "Last_Name", then before printing the field name, replace the underscore with a space. See php solution 4.4)
}
} else {
//$stmt->execute() failed.
$output = "<p>Database operation failed. Please contact the webmaster.";
}
} else {
// statement is not successfully prepared (issues with the query).
$output = "<p>Database query failed. Please contact the webmaster.";
}
} else {
// $missing is not empty
$output = "<p>The following required fields are missing in your form submission. Please check your form again and fill them out. <br>Thank you.<br>\n<ul>";
foreach($missing as $m){
$output .= "<li>$m";
}
$output .= "</ul>";
}
?>
Таким образом, в целом, почему форма возвращения, что поля не хватает, когда я заполнил бы их всех, так что не должно быть никаких нет. И как я могу отправить форму, а не перезагружать и вернуться в начало страницы? Прошу прощения, если есть какая-то необходимая информация, которую я не опубликовал заранее, если вам больше нужны фрагменты кода, пожалуйста, дайте мне знать. Спасибо вам, ребята!
@ Lars благодарит вас за советы! Я буду использовать указатели, которые вы предоставили.Если у меня возникнут проблемы, не забудьте спросить вас. –
После того, как вы внесли изменения, предложенные вами, страница теперь перезагружается и возвращается в начало страницы и не отображает сообщение об ошибке/ошибке. Вы знаете, как его оставить на слайде4 и отобразить сообщение об ошибке/ошибке ниже формы на слайде4? Форма отправляет в мою базу данных прямо сейчас! Итак, это шаг в правильном направлении :). –
все в порядке, не могли бы вы показать мне, что у вас есть? –