2

I'm trying to work out a MySQL query that only adds a new row to an existing table if all fields have a value present, otherwise it should be dropped/ignored.

The query I have at the moment is as follows:

 INSERT INTO markers (`name`, `address`, `details`, `date`, `link`, `lat`, `lng`, `type`)
    VALUES ("{1}", "{2}", "{3}", "{15}", "{4}", "{11}", "{12}", "{5}")

If {15} is left blank by my form then I don't want any of the other values added to the table.

Hope that makes sense!

Thanks

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
Alf1ee
  • 21
  • 3

3 Answers3

3

I would suggest you do a couple of different solutions.

You could setup your database to not allow null values, and then when you go to insert, handle your null errors (probably not the best solution out there though). If you need to have null values, then you will have to handle this in code.

The other thing is to implement form validation. You can do this with JavaScript, code behind, or even both. Both is suggested as some people may have JavaScript disabled on their browser.

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
1

I'd say check the inputs on the front-end with Java, C#, Swift, whatever. Then if an entry is blank, just make a pop-up message letting your user know to fill out every field, or for your application to just skip that record.

scubasteve623
  • 637
  • 4
  • 7
0

If you want to do this directly in MySQL, you can create a trigger that checks the values before they are inserted, and throw an error if some validation rule is not fulfilled.

Example:

delimiter $$
create trigger no_emtpy_values before insert into markers
for each row
begin
    declare msg varchar(255);
    declare condition_fail int default 0;
    -- Write the appropriate validations and set condition_fail to 1
    -- if the validations are not fulfilled. For example:
    if NEW.`date` IS NULL then
        set condition_fail = 1;
    end if;
    -- That "NEW" refers to the row about to be inserted

    -- If the validation rules are not fulfilled, throw an error:
    if condition_fail then
        set msg = "You can't insert the data!";
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg;
    end if;
end $$
delimiter ;

References:

Hope this helps

Community
  • 1
  • 1
Barranka
  • 20,547
  • 13
  • 65
  • 83