gpt4 book ai didi

php - 在php中使用if else语句插入数据库表

转载 作者:行者123 更新时间:2023-11-29 10:55:32 25 4
gpt4 key购买 nike

可能是我没问好假设我有两种形式

<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");
}

}

这里的问题是,数据没有插入到数据库中。请问可能出了什么问题?

最佳答案

这是一个赋值,表达式返回bool(true):

if ($reg_as = "导出器")

要比较两个值,您应该使用两个等号:

if ($reg_as == "导出器")

也许你可以做这样的事情:

<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>";
}
}

关于php - 在php中使用if else语句插入数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43097036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com