简体   繁体   English

如果记录已存在,请检查mysql表

[英]Check mysql table if record already exists

I'm using the following to insert company data into a mysql table. 我正在使用以下内容将公司数据插入到mysql表中。 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变量$company是我要检查的内容。

   <?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 在执行插入之前,执行select语句以查看它们是否在那里

  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. 基本上,发送另一个查询以检查具有相同公司名称的重复行,如果查询返回0行,则只运行insert命令。

<?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. 自然的解决方案是先运行另一个查询(例如select count())来检查标记是否存在,并从那里分支条件逻辑。

A more interesting solution would be to use the concept of an UPSERT (Update + Insert). 更有趣的解决方案是使用UPSERT (更新+插入)的概念。 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. 另一种技术涉及创建主键列并利用mysql的完整性检查强制每条记录保留1行。 So the first insert for each primary key would be successful, but all other would fail. 因此,每个主键的第一个插入将成功,但所有其他插入都将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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