2016-01-03 72 views
0

找不到直接的答案。當我點擊提交一次時,我的自定義wordpress php代碼似乎被執行兩次。點擊後,代碼將添加兩個同名的城市。正如你所看到的,我試圖通過檢查重複來避免這種情況,但它忽略了它......我嘗試將html移動到一個函數中,但是在那裏也沒有幫助。現在我的代碼看起來很奇怪,仍然沒有解決方案。任何新想法?SQL插入執行兩次,php

<?php get_header(); ?> 

<div id="primary" class="content-area"> 
    <main id="main" class="site-main" role="main"> 
     <?php 
     // Start the loop. 
     while (have_posts()) : the_post(); 

      // Include the page content template. 
      get_template_part('template-parts/content', 'page'); 

      if (comments_open() || get_comments_number()) { 
       comments_template(); 
      } 

      // End of the loop. 
     endwhile; 
     ?> 

    </main><!-- .site-main --> 

<?php 

function showForm() { 

    echo "<form name='submit' method='post'>"; 
    echo "<select name='countriesSelect'> 
      <option value='-1'>Choose...</option>"; 
    $conn = new mysqli('localhost','a','b','c'); 
    $query = "SELECT id,country_name FROM countries"; 
    $result = $conn->query($query); 

    while($row = $result->fetch_assoc()) { 
     echo "<option value='" . $row['id'] . "'>" . $row['country_name'] . "</option>"; 
    } 
    $conn->close(); 
    echo "</select><br /><br /> 

     Now choose a new city:&nbsp;&nbsp;<input type='text' name='cityname' maxlength='30' size='30' value='' style='width: 300px;' /><br /><br /> 

     That is it: <br /> 
     <input type='submit' value='Add new city' /><br /><br /> 
    </form>"; 
    return; 
} 

if (!empty($_POST['cityname']) && !empty($_POST['countriesSelect'])) { 

    $cityname = $_POST['cityname']; 
    $countriesSelect = $_POST['countriesSelect']; 

    // make sure city doesn't exist - also because for some unknown reason this script is called twice =/ 
    $db = new mysqli('localhost','a','b','c'); 
    $query = "SELECT city_name FROM cities WHERE city_name='$cityname'"; 
    $result = $db->query($query); 
    $row = $result->fetch_assoc(); 
    if (empty($row['city_name'])) { 

     // add new city 
     $query = "INSERT INTO cities (country_id, city_name, amount_raised_usd) VALUES ($countriesSelect, '$cityname', 0)"; 
     $result = $db->query($query); 

     if ($db->query($query) === TRUE) { 
      echo "<div style='color: green;'>New city added successfully. Add another?"; 
     } else { 
      echo "<div style='color: red;'>Error: " . $query . " :: " . $db->error; 
     } 

     echo '</div><br /><br />'; 
    } 

    $db->close(); 
    showForm(); 

} else { 
    showForm(); 
} 
?> 

    <?php get_sidebar('content-bottom'); ?> 

</div><!-- .content-area --> 

<?php get_footer(); ?> 

回答

2

你看到這個

$result = $db->query($query); 

下一行:

if ($db->query($query) === TRUE) { 

這意味着,在運行查詢兩次。取下$db->query之一,例如:

$result = $db->query($query); 
if ($result === TRUE) { /* do stuff */ 
1

你執行兩次查詢:

$result = $db->query($query); 
if ($db->query($query) === TRUE) { 

應該是:

$result = $db->query($query); 
if ($result === TRUE) {