php – How can i check database if exist from in array-ThrowExceptions

Exception or error:

i try to check before insert database if values exist in database row.

this is my code. i want to check in array values if have in database. if exist “kullanici” and “totoid” dont insert to database.

            if($sonuc == 1) {
                $arr[] = '(
                                "' . $mac->kullanici . '",
                                "5",
                                "' . $mac->totoid  . '"
                        )';
            }
            if($sonuc == 2) {
                $arr[] = '(
                                "' . $mac->kullanici . '",
                                "10",
                                "' . $mac->totoid  . '"
                        )';
            }
            if($sonuc == 3) {
                $arr[] = '(
                                "' . $mac->kullanici . '",
                                "15",
                                "' . $mac->totoid  . '"
                        )';
            }
            if($sonuc == 4) {
                $arr[] = '(
                                "' . $mac->kullanici . '",
                                "20",
                                "' . $mac->totoid  . '"
                        )';
            }
            if($sonuc == 5) {
                $arr[] = '(
                                "' . $mac->kullanici . '",
                                "25",
                                "' . $mac->totoid  . '"
                        )';
            }
        }

        $sql = $this->db->query("INSERT INTO kazananlar (kullanici, kazanci, totoid) VALUES " . implode(',', $arr));

enter image description here

How to solve:

I would suggest using the insert... on duplicate key syntax. The upside of this technique is you can use a single query, so you do not have to worry about possible race conditions.

This works by first creating a unique constraint on columns kullanici and totoid:

create unique index idx_kazananlar on kazananlar(kullanici, totoid);

Then, you can do:

insert into kazananlar (kullanici, kazanci, totoid) 
values (...)
on duplicate key update kullanici = values(kullanici)

The database checks if a row already exists with the same kullanici and totoid; if it does, then the on duplicate keys clause performs a no-op.

Leave a Reply

Your email address will not be published. Required fields are marked *