可能我没有问好 我们说我有两种形式
<form action="reg.php" method="post" enctype="multipart/form-data">
<input type="text" name="reg_as" id="export" value="exporter">
<input type="submit" name="reg">
</form>
<form action="reg.php" method="post" enctype="multipart/form-data">
<input type="text" name="reg_as" id="import" value="importer">
<input type="submit" name="reg">
</form>
如何使用if else条件插入多个表 的 reg.php
$reg_as = strip_tags(@$_POST['reg_as']);
$reg = strip_tags(@$_POST['reg']);
$exporter = "exporter";
$importer = "importer";
if ($reg)
{
if ($reg_as == $exporter)
{
$sql =<<<EOF
INSERT INTO exporter (reg_as)
VALUES ('$reg_as');
EOF;
$stmt = $db->exec($sql);
if (!$stmt)
{
echo "<script>alert('There was an error some where!.. Please try again')</script>";
}
else
{
header("Location: index.php");
}
if ($reg_as == $importer) {
$sql = <<<EOF
INSERT INTO importer (reg_as)
VALUES ('$reg_as');
EOF;
}
$stmt = $db->exec($sql);
if (!$stmt)
{
echo "<script>alert('There was an error some where!.. Please try again')</script>";
}
else
{
header("Location: index.php");
}
}
这里的问题是,数据不会插入到数据库中。请问有什么不对?
答案 0 :(得分:1)
这是一个赋值,表达式返回bool(true)
:
if ($reg_as = "Exporter")
要比较这两个值,您应该使用两个相等的符号:
if ($reg_as == "Exporter")
也许你可以这样做:
<form action="reg.php" method="post" enctype="multipart/form-data">
<select name="type" id="type">
<option value="importer">Importer</option>
<option value="exporter">Exporter</option>
</select>
<input type="text" name="reg_as" placeholder="Insert your data here..." />
<input type="submit" name="submit" value="Save">
</form>
<?php
if (!empty($_POST['submit'])) {
$type = in_array($_POST['type'], ['exporter', 'importer']) ? $_POST['type'] : false;
$value = $_POST['reg_as'];
switch ($type) {
case 'exporter':
$query = "INSERT INTO exporter (reg_as) VALUES (:reg_as)";
break;
case 'importer':
$query = "INSERT INTO importer (reg_as) VALUES (:reg_as)";
break;
default:
throw new Exception('Handle your error here!');
break;
}
$statement = $db->prepare($query);
$insert = $statement->execute([':reg_as' => $value]);
if ($insert) {
header("Location: index.php");
} else {
echo "<script>alert('There was an error some where!.. Please try again')</script>";
}
}