如何在插入表之前验证变量是否存在?

时间:2014-07-27 02:45:58

标签: php mysqli

如何验证$ projectname是否存在并阻止它插入时弹出窗口指示错误"此项目已存在"?我还想阻止任何空插入。

请帮忙!

$con=mysqli_connect("127.0.0.1", "root", "password","agent");

$idq="SELECT id_project, projectname FROM project, agentsInfo
WHERE (agentsInfo.idagency = project.id_agent) AND email = '$_SESSION[email]'" or   die(mysql_error());


$result= mysqli_query($con, $idq);

$row_number = 1;

while ($row = $result->fetch_assoc()){

$id_agent= $row["id_agentid_agent"];
$id_project= $row["id_project"];
$projectname= $row["projectname"];


$id_project++;

$row_number++;


}

if (isset($_POST['submit'])) {

if ($projectname != $_POST['projectname']) {




$sql = "INSERT INTO project (id_project, projectname, id_agent)
VALUES ( ?,?, ( select idagency FROM agentsInfo WHERE email = ?))
ON DUPLICATE KEY UPDATE  //this is unnecessary, how do i replace this? 
`id_agent` = VALUES(`id_agent`),
`projectname` = VALUES(`projectname`)
";

if (($stmt = $con->prepare($sql)) === false) {
trigger_error($con->error, E_USER_ERROR);
}

$result= mysqli_query($con, $idq);

$row_number = 1;

while ($row = mysqli_fetch_array($result)) {

$id_project= $row["id_project"];

$id_project++;

}

if ($stmt->bind_param("sss",
$id_project,
$_POST["projectname"],
$_SESSION["email"]) === false) {
trigger_error($stmt->error, E_USER_ERROR);

}


if (($stmt->execute()) === false) {
trigger_error($stmt->error, E_USER_ERROR);
}

} else {

//DUPLICATE FOUND

echo "<script type='text/jscript'>alert('This project already exists.')</script>";

}

}

?>

1 个答案:

答案 0 :(得分:0)

$con=mysqli_connect("127.0.0.1", "root", "password","agent");
// New code
$query="Select count(*) as qty from project where projectname='".$projectname."'";
$result=mysqli_query($query);
$row=mysqli_fetch_array($query);
echo '<SCRIPT type="text/javascript">function doesexist() {';
if($row['qty']>0)
 {
 echo "alert('This project already exists!');";
 }
echo "return();\n}</SCRIPT";
// End of new code
$idq="SELECT id_project, projectname FROM project, agentsInfo
WHERE (agentsInfo.idagency = project.id_agent) AND email = '$_SESSION[email]'" or   die(mysql_error());

只需将“doesexist()”调用添加到正文的onload事件中即可。如果没有项目存在,则只返回,如果存在,则会发出警报。我没有测试过这段代码,因此可能存在语法问题,但概念很合理。