检查现有患者的数据库,然后添加if不存在

时间:2013-03-17 20:09:15

标签: php mysql if-statement

我创建了一个页面,其中mysql查询检查数据库中是否已存在患者,如果患者不存在,则以下代码应将其添加到数据库中

 <?php
    include("includes/staffmenu.php");
    include("includes/staffsession.php");
    @require_once("includes/dbconfig.inc");

    $firstname=$_POST["pfname"];
    $middlename=$_POST["pmname"];
    $surname=$_POST["psname"];
    $nat=$_POST["pnat"];
    $DOB=$_POST["pdob"];
    $pemail=$_POST["pemail"];
    $add1=$_POST["padd1"];
    $add2=$_POST["padd2"];
    $add3=$_POST["padd3"];
    $postcode=$_POST["ppcode"];
    $telephone=$_POST["pphone"];

        $pcheck=mysql_query("
        SELECT * FROM patient 
        WHERE 
        Patient_First_Name='$firstname' AND Patient_Middle_Name='$middlename' AND Patient_Surname='$surname' AND Patient_National_Insurance_No='$nat' 
        AND Patient_DOB='DOB' AND Patient_Address_Line_1='$add1' AND Patient_Address_Line_2='$add2' AND Patient_Address_Line_3='$add3' AND Patient_Postcode='$postcode'");
        $myrow = mysql_fetch_row($pcheck);
            if($myrow)
                    {   echo "This Patient already exists.<br><br> Please press the back button on your browser or the backspace button on your keyboard to go back";

                    }
            else
                    {   mysql_query("INSERT INTO patient (Patient_First_Name,Patient_Middle_Name,Patient_Surname,Patient_National_Insurance_No,Patient_DOB,Patient_Email,Patient_Address_Line_1,Patient_Address_Line_2,Patient_Address_Line_3,Patient_Postcode,Patient_Phone_No  ) 
                        VALUES('$firstname','$middlename','$surname','$nat','$DOB','$pemail','$add1','$add2','$add3','$postcode','$telephone')") or die (mysql_error());
                        echo "<br>";
                        echo "<p>Success! The Patient has been added to the database
                        </p>";
                    }   
    ?>

问题在于,即使病人已经存在,也会继续添加一个新的...有人可以告诉我哪里出错了吗?

2 个答案:

答案 0 :(得分:0)

搜索DOB时,您错过了$

Patient_DOB='$DOB'

另外,请注意您的代码容易受到SQL注入攻击

答案 1 :(得分:0)

尝试更改

Patient_DOB='DOB'

Patient_DOB='$DOB'