Question: I'm using the following to insert company data into a mysql table. Is is possible to check if the company is already in the database first before it tries to enter it in again? The php variable `$company` is what I want to check against.

```
   <?php
    require("database.php");
    // Opens a connection to a MySQL server
    $con = mysql_connect("localhost", $username, $password);

    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("medicom_wp", $con);

    $pages = get_posts(array(
        'orderby' => 'title', 
        'post_type' => 'members',
        'numberposts' => 300,
        'post_status' => 'any'  
        ));
        foreach($pages as $post) {
        setup_postdata($post);

        $company = get_field('company_name');
        $address = get_field('address');
        $city = get_field('city');
        $post_code = get_field('post_code');

        mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
        }
        wp_reset_query();

    mysql_close($con);
    ?>

```

Answer: 
1. Do a select statement to see if they are in there before doing the insert
2. (Not recommended) make the name field (or any other field that idnentifies a company, a unique key so when you try to enter it again it is rejected
The natural solution would be to run another query prior (e.g. select count()) to check if the marker exists, and branch your conditional logic from there.

A more interesting solution would be to use the concept of an **UPSERT** (Update + Insert). An upsert inserts the row if it doesn't exist, and updates it if it does exists. So effectively there will be only 1 row in the end regardless, but this is assuming you don't mind overwriting the data. [Here's a sample SO question about that.](https://stackoverflow.com/questions/1218905/how-do-i-update-if-exists-insert-if-not-aka-upsert-or-merge-in-mysql)

Another technique involves creating a primary key column and taking advantage of mysql's integrity checks to forcefully keep 1 row per record. So the first insert for each primary key would be successful, but all other would fail.