简体   繁体   中英

Check mysql table if record already exists

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);
    ?>
  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

Try the following. Basically, sending another query to check for a duplicate row with the same company name and if the query returns 0 rows then only run the insert command.

<?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');

    // prepare query to check for duplicate company
    $sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
    // run query
    $row_dup = mysql_fetch_assoc(mysql_query($sql,$conn));
    // if no row exist
    if ($row_dup['cnt'] == 0) {
        // insert new company
        // consider preparing this query using sprintf() and mysql_real_escape_string() as above
        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);
?>

The natural solution would be to run another query prior (eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM