【发布时间】:2018-08-09 17:18:37
【问题描述】:
我正在尝试使用单个 .php 页面来获得基于用户角色的条件 MySQLi INSERT。基本上,除了几个字段之外,INSERT 非常相似。这是我的代码:
require 'scripts/config.php';
if ($_SESSION['role'] == 'admin')
{
$sql = "INSERT INTO aircraft_dataV2 (status, ac_cat, ac_type, faa_id, time_in, date_in, time_out, date_out, services, comments, contact_name, contact_phone, contact_ext, contact_email, email, csr_lsr, created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
if($stmt = mysqli_prepare($link, $sql))
{
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssssssssssssssss", $status, $ac_cat, $ac_type, $faa_id, $time_in, $date_in, $time_out, $date_out, $services, $comments, $contact_name, $contact_phone, $contact_ext, $contact_email, $email, $csr_lsr, $created);
...CODE TO $_REQUEST FORM DATA ...
if(mysqli_stmt_execute($stmt))
{
//Redirect to
$aircraft_id = mysqli_insert_id($link);
header("Location: service_confirm.php?aircraft_id=$aircraft_id");
} else
{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
}
if ($_SESSION['role'] == 'client')
{
SAME as above minus the $csr/lsr and $email fields
}
无论用户 $_SESSION 是什么,都会执行两个 INSERT 语句。一个条目是空白的,另一个条目根据提交的表格包含正确的数据。
我的表单是相同的,除了几个基于管理员和客户端不同的条件字段。
我可以这样做还是需要返回到具有两个不同 .php 页面的原始脚本,其中包含管理员与客户端的 INSERT 语句,如下所示:
if ($_SESSION['role'] == 'admin')
{
header("Location: admin.php")
}
if ($_SESSION['role'] == 'client')
{
header("Location: client.php")
}
【问题讨论】:
-
是时候阅读
switch语句或使用关联数组查找表(例如array('admin' => 'admin.php', 'client' => 'client.php')而不是这些if语句的混乱。 -
回答您的问题,是的,您可以这样做。但是,这里有些不对劲。你能告诉我们更多的代码吗?你的表格是什么样的?此外,向我们展示更多包含 SQL 语句的文件。
-
您的表单如何调用此代码?我怀疑这段代码被调用了两次(可能是标题/重定向)。您没有检查表单是否已提交。
-
表单动作与 php 代码所在的页面相同。我进行了验证,并且我还在检查是否记录了活动会话以及是否已提交表单......试图不发布超过 400 行代码。
标签: php mysql session if-statement mysqli