У меня есть несколько форм на одной странице, и я обрабатываю их на другой странице с именем editmenusprocess.php
.
Когда я пытаюсь отправить отдельную форму, информация помещается в базу данных.
Однако все остальные формы также представлены с нулевыми значениями.
Я попытался использовать
if ($_POST['action'] == 'starter')
как работа вокруг.
Я не думаю, что правильно его реализую.
У меня есть несколько таких форм на одной странице.
<?php
if ($_POST['action'] == 'starter') {
}
else if($_POST['action'] == 'main' ){
}
else if($_POST['action'] == 'desert' ){
}
else if($_POST['action'] == 'menus' ){
}
?>
<div class='container-fluid bg-color' style='margin-bottom:20px'>
<div class='row justify-content-center '>
<div class='col-md-4'>
<form action='editmenusprocess.php?action=starter' method='POST'>
<legend>
<h3 style='margin-top: 20px;'>Add Starter</h3>
</legend>
<div class='form-group '>
<label for='exampleInputEmail1'>Food:</label>
<input type='text' class='form-control form-control-lg' name='msfood' placeholder='Title'>
</div>
<div class='form-group '>
<label for='exampleInputEmail1'>Description:</label>
<input type='text' class='form-control form-control-lg' name='msdescript' placeholder='Title'>
</div>
<div class='form-group'>
<label for='exampleInputEmail1'>Price:</label>
<input type='text' class='form-control form-control-lg' name='msprice' placeholder='Info'>
</div>
<button type='submit' class='btn btn-primary bt'>Submit</button>
</form>
</div>
Этот код находится на странице процесса.
$msid = mysqli_real_escape_string($link, $_POST["msid"]);
$msfood = mysqli_real_escape_string($link, $_POST["msfood"]);
$msdescript = mysqli_real_escape_string($link, $_POST["msdescript"]);
$msprice = mysqli_real_escape_string($link, $_POST["msprice"]);
$msinsertquery = "INSERT INTO 2043menustarter (id, food, descript,price) VALUES (null, '$msfood','$msdescript','$msprice')";
$msresult = mysqli_query($link, $msinsertquery) or die (mysqli_error($link));
Я достиг прогресса в этой проблеме, используя подход ($_POST['action'] == 'starter')
и формы теперь вставляют данные в соответствующие таблицы, но при отправке некоторые предупреждения все еще появляются.
Это код на странице редактирования/формы:
<form action ='editmenusprocess.php' method = 'POST'>
<legend><h3 style = 'margin-top: 20px;'>Add Starter</h3></legend>
<div class='form-group '>
<label for='fd1'>Food:</label>
<input type='text' class='form-control form-control-lg' name='msfood' id="fd1">
<input type="hidden" name="action" value="starter">
</div>
<div class='form-group '>
<label for='fd2'>Description:</label>
<input type='text' class='form-control form-control-lg' name='msdescript' id="fd2">
<input type="hidden" name="action" value="starter">
</div>
<div class='form-group'>
<label for='fd3'>Price:</label>
<input type='text' class='form-control form-control-lg' name = 'msprice' id=fd3>
<input type="hidden" name="action" value="starter">
</div>
<button type='submit' class='btn btn-primary bt'>Submit</button>
</form>
</div>
<div class= 'col-md-4'>
<form action ='editmenusprocess.php' method = 'POST'>
<legend><h3 style = 'margin-top: 20px;'>Add Main</h3></legend>
<div class='form-group '>
<label for='st1'>Food:</label>
<input type='text' class='form-control form-control-lg' name='mmfood' id="st1">
<input type="hidden" name="action" value="main">
</div>
<div class='form-group '>
<label for='st2'>Description:</label>
<input type='text' class='form-control form-control-lg' name='mmdescript' id='st2'>
<input type="hidden" name="action" value="main">
</div>
<div class='form-group'>
<label for='st3'>Price:</label>
<input type='text' class='form-control form-control-lg' name = 'mmprice' id='st3'>
<input type="hidden" name="action" value="main">
</div>
<button type='submit' class='btn btn-primary bt'>Submit</button>
</form>
это теперь код на странице процесса:
$action = (!empty($_POST["action"]))?$_POST["action"]:null;
$msfood = mysqli_real_escape_string($link, $_POST["msfood"]);
$msdescript = mysqli_real_escape_string($link, $_POST["msdescript"]);
$msprice = mysqli_real_escape_string($link, $_POST["msprice"]);
$mmfood = mysqli_real_escape_string($link, $_POST["mmfood"]);
$mmdescript = mysqli_real_escape_string($link, $_POST["mmdescript"]);
$mmprice = mysqli_real_escape_string($link, $_POST["mmprice"]);
if($action == 'starter'){
$stmt = $link->prepare("INSERT INTO 2043menustarter (id,food, descript, price) VALUES (null, '$msfood','$msdescript','$msprice')");
$stmt->bind_param('sss',$_POST["msfood"], $_POST["msdescript"], $_POST["msprice"]);
$stmt->execute();
$stmt->close();
}else if($action == 'main'){
$stmt = $link->prepare("INSERT INTO 2043menumain (id,food, descript, price) VALUES (null, '$mmfood','$mmdescript','$mmprice')");
$stmt->bind_param('sss',$_POST["mmfood"], $_POST["mmdescript"], $_POST["mmprice"]);
$stmt->execute();
$stmt->close();
}
Если вы хотите, чтобы action
было прочитано как POST, попробуйте поместить его в скрытый ввод. Одна из ваших форм будет выглядеть так:
<form action="editmenusprocess.php" method="POST">
<legend><h3 style="margin-top: 20px;">Add Starter</h3></legend>
<div class="form-group">
<label for="exampleInputEmail1">Food:</label>
<input type="text" class="form-control form-control-lg" name="msfood" placeholder="Title">
<input type="hidden" name="action" value="starter">
</div>
<!-- THE REST OF THE INPUT FIELDS BELOW -->
Сделайте все остальное в своих других формах.
Затем в файле editmenusprocess.php:
$action = (!empty($_POST["action"]))?$_POST["action"]:null;
if($action == 'starter'){
$stmt = $link->prepare("INSERT INTO 2043menustarter (food, descript, price) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $_POST["msfood"], $_POST["msdescript"], $_POST["msprice"]);
$stmt->execute();
$stmt->close();
}
/*** THEN THE REST OF YOUR OTHER CONDITIONS BELOW ***/
В разделе комментариев вашего сообщения люди предлагали вам хотя бы использовать подготовленное выражение. Вы можете прочитать об этом здесь.
Значение действия закодировано в строке запроса.
PHP анализирует строку запроса в $_GET
. Только данные из тела запроса будут проанализированы в $_POST
файле $_POST
.
Используйте $_GET['action']
или переместите данные из строки запроса на вход.
если вы хотите, чтобы поле было отправлено другому сценарию отдельно, у вас есть 2 варианта.
<form method="post" action="somescript.php">
<input type="text" name="input1"><button type="submit">save</button>
</form>
<form method="post" action="somescript.php">
<input type="text" name="input1"><button type="submit">save</button>
</form>
$('form').submit(function(e){
e.preventDefault();
// clean your data
var yourCleanedData = [];
$('form input').each(functionn(idx, elm){
if (elm.value){
yourCleanedData[elm.name] = elm.value;
}
});
$.ajax({
url: 'somescript.php',
type: 'POST',
data: yourCleanedData,
})
});