2013-03-13 71 views
-1

我一直在從這個網站的幫助下工作。我現在可以插入players表多行(基於$add-rows值)。我還需要將events表格1行插入。當我提交表單,將其插入到players罰款,但不進eventsphp mysqli插入多行到1表和1行到另一個表

這是我的形式需要2所有值查詢

<form id="form-add" name="form-add" method="POST" enctype="multipart/form-data" action="page.php"> 
<input name="add-name" id="add-name" type="text" value="Event"> 
<input name="add-start" id="add-start" type="text" value=""> 
<input name="add-end" id="add-end" type="text" value=""> 
<input name="add-loc" id="add-loc" type="text" value=""> 
<input name="add-rows" id="add-rows" type="text" value=""> 
<input name="add-submit" id="add-submit" type="submit" value="Add" /> 
<input type="hidden" name="submitted" value="TRUE" /> 
</form> 

這些都是我從形式張貼值

<?php 
$add_name = $_POST['add-name']; 
$add_start = $_POST['add-start']; 
$add_end = $_POST['add-end']; 
$add_loc = $_POST['add-loc']; 
$add_rows = $_POST['add-rows']; 
$add_url = date('Y-m-d',strtotime($add_start)).'-'.str_replace('-',' ',($add_name)); 

if(isset($_POST['submitted'])) { //check if form submitted 
    //connection 
    $mysqli = new mysqli('host', 'user', 'pass', 'db_name'); 

    //this is the first query - to insert multiple rows in to players table (from same form) 
    $query = "INSERT INTO players (position, event, start, end, name, one, two, three, four, five, six) 
     VALUES ('', '$add_url', '$add_start', '$add_end', '', 'Yes', 'No', 'No', 'No', 'No', 'No');" . 
     str_repeat(", ('', '$add_url', '$add_start', '$add_end', '', 'Yes', 'No', 'No', 'No', 'No', 'No')", $add_rows - 1); 

    //this is the 2nd query - to insert to events table (from same form) 
    $query .= "INSERT INTO events (ur, name, start, end, loc) VALUES ('$add_url', '$add_name' '$add_start', '$add_end', '$add_loc');"; 

    // execute query - $result is false if the first query failed 
    $result = mysqli_multi_query($mysqli, $query); 

    if ($result) { 
     do { 
      // grab the result of the next query 
      if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '') { 
       echo "Query failed: " . mysqli_error($mysqli); 
      } 
     } while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results 
    } else { 
     echo "First query failed..." . mysqli_error($mysqli); 
    } 
}//end of form submit if 
?> 
+0

@你的常識我需要輸入x行數bcz沒有名字(名字列在玩家表中)。那些將在稍後更新。但需要x個插槽(行)。關於multi_query,我試過了,沒有運氣。我可以插入到玩家表中,但不是事件。我現在要通過我的代碼..調試,因爲你建議,但沒有運氣。謝謝 – Azukah 2013-03-13 02:16:24

回答

1

有你的代碼3個主要故障

  1. 您正在使用mysqli_multi_query()這是沒用的,只會讓你的代碼過於複雜。
  2. 您沒有使用佔位符,這會使您的代碼容易受到注入攻擊
  3. 您正在數據庫中插入相同的行,這是違反數據庫法律的罪行。

因此,進行2個查詢:一個插入1個記錄到玩家表中,另一個插入1個記錄到事件中。
使用預處理語句在兩個獨立的調用中運行它們。
由於mysqli不適用於他們 - 請使用PDO。

相關問題