2016-11-16 36 views
-1

當我點擊我的「創建」按鈕時,我希望將記錄添加到我的類別表中,但由於某種原因它正在被添加兩次 - 即使我只是單擊該按鈕一次。任何想法,爲什麼這可能是?我看不到還有什麼地方可以調用
if (isset($_POST['create'])) {。我的整個項目只有4頁。誰能告訴我爲什麼這行被插入兩次到我的數據庫?

<?php require('dbConnect.php'); 

    //use the variables we created in volleyLogin.php 
     session_start(); 
     $username = $_SESSION['username']; 
     $user_id = $_SESSION['user_id']; 
     echo "user name is " . $username . "<br>"; 
     echo "user id is " . $user_id . "<br>"; 

    if (isset($_POST['create'])) { 

     $category = ($_POST['category']); 
     $name = ($_POST['name']); 
     $phonenumber = ($_POST['phonenumber']); 
     $address = ($_POST['address']); 
     $comment = ($_POST['comment']); 

    //check if the category being entered is already there 
     $check="SELECT COUNT(*) FROM category WHERE cat_name = '$_POST[category]'"; 
     $get_value = mysqli_query($con,$check); 
    //check the number of values of the category being posted 
     $data = mysqli_fetch_array($get_value, MYSQLI_NUM); 
    //if the category name already exists in the category table 
     if($data[0] >= 1) { 
     echo "This Already Exists<br/>"; 
     } 

     else if ($data[0] < 1) 
     { 
    //if it's not in there, then add the category in the category table. 

     $sql = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')"; 
     $rs1=mysqli_query($con, $sql); 

     if ($con->query($sql) === TRUE) { 
     echo "Yes, it's been added correctly"; 

     } else { 
     echo "Error: " . $sql . "<br>" . $con->error; 
     } 

     } 
    $con->close(); 
     } 



    ?> 

     <!doctype html> 
     <html> 
     <body> 
     <h2>Create new Contact</h2> 
     <form method="post" action="" name="frmAdd"> 
     <p><input type="text" name = "category" id = "category" placeholder = "category"></p> 
     <p><input type="text" name = "name" id = "name" placeholder = "name"></p> 
     <p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p> 
     <p><input type="text" name = "address" id = "address" placeholder = "address"></p> 
     <p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p> 

     <p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p> 
     <a href="exit.php">Exit</a> 

     </form> 

     </body> 
     </html> 

回答

4

你正在運行的$sql查詢兩次,用兩種不同的方法:

$rs1=mysqli_query($con, $sql); 

     if ($con->query($sql) === TRUE) { 

這就是爲什麼你要重複的條目。

您應該刪除$rs1,因爲它沒有被使用,或者驗證它的條件值,而不是再次運行該函數。

+0

謝謝。我不明白它爲什麼有效,但它確實有效。現在我將在一本新書中讀到這些部分,PHP是Web。顯然,我會在9分鐘內接受你的回答。 – CHarris

+2

沒關係。你可能只是混淆了兩個不同的東西。當你在這,檢查了這一點:[我怎樣才能防止SQL注入PHP](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) 。你的代碼非常脆弱。切勿將輸入數據直接放入查詢中。永遠不要相信他們,他們可以全部哈克哈克。使用'mysqli_real_escape_string'或使用預準備語句。 – Phiter

相關問題