Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2010
    Posts
    119
    Thanks
    6
    Thanked 0 Times in 0 Posts

    checking mysql record exists problem

    hi again

    hi ,,,, i have a table cost with

    cost no( Unique) , name , and officer in the field names in the table

    i want to insert some records to cost table ....

    i want to check there cost no exists or not before record adding to the table

    example

    in the cost table i have cost no -50

    now i going to insert Cost no-50 ,51 and 52

    it should only insert 51 , 52 because cost no 50 is already there( 50 should not be replace with new record 50 )

    plz give me SQL QUERY for this

    help meeeeeeeeeeeee

  • #2
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts
    Set them seperately as normal, and the database will refuse to set the one with cost=50 because it's unique.
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog

  • #3
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    Lamped is right, you can allow MySQL to attempt the INSERT and it will just fail if that value already exists. However, this is entirely dependant on whether you set up a unique index for that column. If you are just saying you want that column to be unique, but you didn't create an index to enforce uniqueness, then you'll have to SELECT first, and then insert if the select returns nothing.

    p.s. Assuming you do have a unique index, you can find out if the INSERT worked or not by calling mysql_affected_rows() after the insert query and testing the return value: 0 means no row was inserted, 1+ means a row was inserted.

    http://us2.php.net/manual/en/functio...ected-rows.php


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •