MySQL:如果插入值不唯一,则返回错误

时间:2015-08-05 13:21:42

标签: php html mysql

如果firstname和last name的组合已经在Student表中,我想在addStudent.php页面上输出错误。目前,它不会在表中添加非唯一条目,但不会通知用户该条目已存在。

表格结构:

<?php
include 'connect.php';

// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
fname VARCHAR(30),
lname VARCHAR(30),
mclass VARCHAR(30),
aclass VARCHAR(30),
UNIQUE (`fname`, `lname`)
)";

if ($conn->query($sql) === TRUE) {
} else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

addStudent.php

    <fieldset>
        <legend><h2> Details </h2></legend>
        <form class="pure-form">
        <label>First Name&nbsp;&nbsp; </label><input type="text" id="firstname" name = "firstname" autofocus=""><br><br>
        <label>Last Name&nbsp;&nbsp; </label><input type="text" id="lastname" name = "lastname"><br><br>    
        </form>
    </fieldset>
    <br>
    <fieldset>
        <legend><h2>Classes</h2></legend>
        <form class="pure-form">
        <label>Morning Class&nbsp;&nbsp;  </label>
            <select id = "morningclass" name="morningclass">
              <option value=""> </option>
              <option value="G1F">G1-F</option>
              <option value="G1S">G1-S</option>
              <option value="G2J">G2-J</option>
              <option value="G2A">G2-A</option>
              <option value="G3">G3</option>
              <option value="G4">G4</option>
              <option value="G5">G5</option>
            </select>
        <br> <br>
        <label>Afternoon Class&nbsp;&nbsp; </label>
            <select id = "afternoonclass" name = "afternoonclass">
              <option value=""> </option>
              <option value="7P">7P</option>
              <option value="7H">7H</option>
              <option value="8P">8P</option>
              <option value="8H">8H</option>
              <option value="9">9</option>
              <option value="10">10</option>
              <option value="11">11</option>
            </select>
        <br> <br>
        </form>
    </fieldset>

    <br>
    <div class="buttonAlign">
    <input type="button" value="Cancel" onclick="cancel();" class="button-error pure-button"> &nbsp;
    <input type="button" value="Add" id="button"  class="button-secondary pure-button">
    </div>
    <br>

    </body>
</div > 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
 $(document).ready(function(){

        $("#button").click(function(){

              var fname=$("#firstname").val();
              var lname=$("#lastname").val();
              var mclass=$("#morningclass").val();
              var aclass=$("#afternoonclass").val();
        if (fname !== "" && lname !== "" && mclass !== "" && aclass !== "") {
              $.ajax({
                  type:"post",
                  url:"add.php",
                  data:"firstname="+fname+"&lastname="+lname+"&morningclass="+mclass+"&afternoonclass="+aclass,
                  success:function(){
                     alert("Entry added");
                     window.location.href = "viewStudent.php";
                  }

              });
            document.getElementById("firstname").value = "";
            document.getElementById("lastname").value = "";
            document.getElementById("morningclass").value = "";
            document.getElementById("afternoonclass").value = "";
        } else {
            alert("You must fill out all the empty information!");
        }

        });     

});

function cancel() {
    window.location.href = "viewStudent.php";
}
</script> 

add.php

<?php
include 'connect.php';

$fname=preg_replace('/[^a-z]/', "", strtolower($_POST["firstname"]));
$lname=preg_replace('/[^a-z]/', "", strtolower($_POST["lastname"]));
$mclass=$_POST["morningclass"];
$aclass=$_POST["afternoonclass"];

$sql=("INSERT INTO student(fname,lname,mclass,aclass) values('$fname','$lname','$mclass','$aclass')");

if ($conn->query($sql) === TRUE) {
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

2 个答案:

答案 0 :(得分:0)

存储过程不是通过php将调用分离到select和update语句,而是在服务器上执行驴工作。使用这种方法,您不需要多个帖子到各个页面......

basic sql stored procedure
--------------------------
create procedure `spAddUser`(IN `param_forename` VARCHAR(64), IN `param_surname` VARCHAR(64) )
    language sql
    not deterministic
    contains sql
    sql security definer
    comment ''

begin
    declare dbrecords integer default 0;
    declare strsql varchar(10000);
    declare forename varchar(64);
    declare surname varchar(64);
    set @forename=cast(param_forename as char character set utf8);
    set @surname=cast(param_surname as char character set utf8);

    /* Does the user already exist? */

    set @strsql=concat("select distinct count(*) into @dbrecords from `users` where `forename`=@forename and `surname`=@surname;");
        prepare stmt from @strsql;
        execute stmt;
        deallocate prepare stmt;

    if( @dbrecords > 0 ) then
        /* user exists, return statement that tells of problem */
        set @strsql=concat("select 'sorry, that combination of firstname and lastname already exists' as 'result'");
            prepare stmt from @strsql;
            execute stmt;
            deallocate prepare stmt;
    else
        /* all good, add the record */
        set @strsql=concat("insert into `users` set `forename`=@forename, `surname`=@surname;");
            prepare stmt from @strsql;
            execute stmt;
            deallocate prepare stmt;

        set @strsql=concat("select 'Thankyou, your details have been added to the database' as 'result'");
            prepare stmt from @strsql;
            execute stmt;
            deallocate prepare stmt;
    end if;     
end


php
---

$sql="call `spAddUser`('$forename','$surname')";
$db->query( $sql ); //etc

答案 1 :(得分:0)

您的代码大部分都是正常的(除了SQL注入漏洞之外)。您需要做的就是查看尝试插入副本时返回的mysql错误信息,以确定是否遇到了唯一的约束违规或是否出现其他问题。

有关如何检测唯一约束违规的问题,请参阅此另外的问题 - PHP - detect mysql update/insertion failure due to violated unique constraint