2012-06-14 41 views
0

我使用以下內容將公司數據插入到mysql表中。是否有可能在再次嘗試重新輸入之前檢查公司是否已經在數據庫中? php變量$company是我想要檢查的。如果記錄已存在,請檢查mysql表

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

請嘗試以下操作。基本上,發送另一個查詢來檢查具有相同公司名稱的重複行,如果查詢返回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); 
?> 
1
  1. 做一個select語句,看看他們都在那裏做插入之前

  2. (不推薦)使name字段(或idnentifies公司任何其他領域,獨特的鍵,以便當您嘗試再次輸入被拒絕

0

自然的解決辦法是運行另一個查詢之前(如SELECT COUNT()),以檢查是否存在標誌和分公司您conditio從那裏開始。

更有趣的解決方案是使用UPSERT(更新+插件)的概念。如果不存在,插入該行,如果它存在,則更新它。如此有效地最終只會有1行,不過這是假設你不介意覆蓋數據。 Here's a sample SO question about that.

另一種技術是創建一個主鍵列並利用mysql的完整性檢查來強制保留每行記錄一行。因此,每個主鍵的第一個插入將會成功,但其他所有插入都將失敗。

相關問題