1

I am making an Android application. Each time the application closes, it inserts a GCM Registration ID into the database, but there is no need for a single GCM Registration ID to be inserted more than one time.

How does one prevent duplicate data from being inserted into a MySQL database?

    <?php

// response json
$json = array();

/**
 * Registering a user device
 * Store reg id in users table
 */
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $gcm_regid = $_POST["regId"]; // GCM Registration ID
    // Store user details in db
    include_once './db_functions.php';
    include_once './GCM.php';

    $db = new DB_Functions();
    $gcm = new GCM();

    $res = $db->storeUser($name, $email, $gcm_regid);

    $registatoin_ids = array($gcm_regid);
    $message = array("product" => "shirt");

    $result = $gcm->send_notification($registatoin_ids, $message);

    echo $result;
} else {
    // user details missing
}
?>
Ryan Vincent
  • 4,483
  • 7
  • 22
  • 31
Raul
  • 11
  • 2
  • 2
    possible duplicate of [Best way to test if a row exists in a MySQL table](http://stackoverflow.com/questions/1676551/best-way-to-test-if-a-row-exists-in-a-mysql-table) – Ohgodwhy Apr 19 '14 at 04:27

3 Answers3

2

I would use the MySQL Unique Constraint for this:

http://dev.mysql.com/doc/refman/en/constraint-primary-key.html

Otherwise, you can enact this programmatically by only inserting if an identity query produces an empty result.

srage
  • 990
  • 1
  • 9
  • 27
0

What I usually do is I find out wheter or not the row exists, if it does, I update it, otherwise I insert it.

Simon Corcos
  • 962
  • 14
  • 31
0

If you want prevent entering duplicated data into your columns, make that columns unique.

Lost Koder
  • 864
  • 13
  • 32