首先,如果我选择“书包和汤”并单击“ 保存”按钮,则值将保存在数据库中,并重定向到 saveoutofstock.php < / strong>页面。很好....
第二次,如果我选择相同的选项-“ schoolbag&Soup”,则它不会保存在数据库中[因为我在ALTER TABLE outofstock ADD UNIQUE account_prod (name(90), type(90));
之前执行了此操作,但仍然重定向到saveoutofstock.php页面。但我不想重定向,而是要显示错误消息为名称并且类型已经存在
表格
<form name="adduserforms" id="adduserforms" action="saveoutofstock.php" >
<select name="names" id="names" onChange="changecat(this.value);">
<option value="A">>A</option>
<option value="B">>B</option>
</select>
<select name="department" id="department" class="username">
<option value="" disabled selected>Select</option>
</select>
<input type="button" id="assign" value="Save" onclick="assignusers();"/>
saveoutofstock.php
<?php
$_SESSION['login_user'];
if(isset($_POST['edituser']) && $_POST['edituser']=="editUsers")
{
if($_SESSION['login_user']=='admin')
{
$sql = "UPDATE outofstock set name='".$name."',type='".$type."' WHERE id=".$_POST['userId'];
}
$redirectUrl="outofstocklist.php";
}
else if
{
$sql = "SELECT * FROM outofstock WHERE names = '".$name."' AND department ='".$type."' ";
echo "name and type already exists";
}
else
{
$sql = "INSERT INTO outofstock (name,type) VALUES ('".$name."','".$type."')";
$redirectUrl="outofstocklist.php";
}
$result = $db_handle->executeUpdate($sql);
?>
答案 0 :(得分:1)
由于您在(name, type)
上具有唯一索引,因此在尝试执行INSERT
时会出错。您应该检查该错误。
$result = $db_handle->executeUpdate($sql);
if (!$result && mysqli_errno($db_handle) == 1022) {
echo "name and type already exist";
}
1022
是重复密钥的MySQL错误代码。
摆脱此代码块:
else if
{
$sql = "SELECT * FROM outofstock WHERE names = '".$name."' AND department ='".$type."' ";
echo "name and type already exists";
}
语法错误,因为if
之后没有任何条件。它也没有做任何有用的事情,因为它回显了在尝试执行获取错误的INSERT
之前,名称和类型已经存在。
答案 1 :(得分:0)
提交表单时,您必须阻止默认操作。
在您的assignusers()
函数上,将此e.preventDefault()
添加到开头
function assignusers(e){
e.preventDefault();
// Rest of your code here
...
}
答案 2 :(得分:0)
您将需要编辑和重新排列代码,如下所示。...
未经测试...
<?php
$_SESSION['login_user'];
if(isset($_POST['edituser']) && $_POST['edituser']=="editUsers"){
if($_SESSION['login_user']=='admin') {
$sql = "UPDATE outofstock set name='".$name."',type='".$type."' WHERE id=".$_POST['userId'];
$result = $db_handle->executeUpdate($sql);
$redirectUrl="outofstocklist.php";
} else {
$sqlnumrow = "SELECT * FROM outofstock WHERE names = '".$name."' AND department ='".$type."' ";
$numrow = $db_handle->count($sqlnumrow );// I don't know what function name is yours to check num rows
if($numrow !=0){
echo "name and type already exists";
} else {
$sql = "INSERT INTO outofstock (name,type) VALUES ('".$name."','".$type."')";
$result = $db_handle->executeUpdate($sql);
$redirectUrl="outofstocklist.php";
}
}
}
?>