开发者

Check or Add to DB quickly

开发者 https://www.devze.com 2023-02-20 00:11 出处:网络
I\'m using apache, php, mysql and code igniter and I have a database set up.In the database I have two columns that both need to be unique in combo:latitude and longitude.

I'm using apache, php, mysql and code igniter and I have a database set up. In the database I have two columns that both need to be unique in combo: latitude and longitude.

So I set up the database using this call:

alter table pano_raw add unique index(lat, lng)

Now when I insert values into the two columns (lat and lng) if the value is the same, the database should reject the write correct?

function addNewSet($da开发者_StackOverflow社区ta)
{
    $this->db->insert('sets', $data);
}

This function should return a true or false, depending on the success of the read or write correct?

So now how so I alter it so that when it will return the row_id of the inserted record or return FALSE? If the write worked, I need the row_id, if it didn't I need FALSE so I can alter the code that called this function.

Would this work? I don't think so. Ideas?

function addNewSet($data)
{
    $this->db->insert('sets', $data);
    return $this->db->insert_id();
}


By default it wont return false, it will have a database error before returning false.

If you really want this, you need to go to application/config/database.php and change set this to false $db['default']['db_debug'] = FALSE;

Then you should be able to do this (assuming your table has an id field set to auto increment)

 function addNewSet($data) {
     if ($this->db->insert('sets', $data)) {
          return $this->db->insert_id(); 
     } else {
          return FALSE;
     }
 }


Try this:

function addNewSet($data)
{
    $result = $this->db->insert('sets', $data);
    if ( $result )
        return $this->db->insert_id();
    return false;
}


You can use $this->db->affected_rows(); after inserting the data to check if any record was added (or affected).

So

function addNewSet($data)
{
    $this->db->insert('sets', $data);

    if($this->db->affected_rows()==1)
    {
        return $this->db->insert_id();
    }
    else
    {
        return false; // nothing was added!
    }
}

Should do it (untested).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号