2013-03-04 129 views
2

我有一個使用for循環的多次插入(4條記錄)。然後,我想在插入path_allowed ='y'的記錄上運行更新查詢(只有四個中的一個具有此值)。我猜LAST_INSERT_ID()在這裏很有用,但不知道如何使用它來更新插入該記錄如下:多次插入後更新特定記錄 - 可能使用last_insert_id()

$pathway_allowed = intval($_POST['allowed']); 
$action = mysql_real_escape_string($_POST['actions']); 

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

$pathway_comment = array(); 
foreach($_POST['comment'] as $comment) { 
    $pathway_comment[]= mysql_real_escape_string($comment); 
} 
for($i=0, $count = count($pathway_comment);$i<$count;$i++) { 
    $comment = $pathway_comment[$i]; 
    $query = sprintf(
     "INSERT INTO pathway (    
      pathway_pk, 
      case_fk, 
      level, 
      pathway_action_fk, 
      pathway_allowed, 
      comment 
     ) VALUES (
      '', 
      '$case_pk', 
      '1', 
      '$action', 
      '%s', 
      '$comment')", $pathway_allowed === $i ? 'y' : 'n'); 

     $result = mysql_query($query, $connection) or die(mysql_error()); 
} 
if($result){ 
- SELECT the 4 records here... 
} 
} 
+0

彼得,你應該知道'mysql_query'將來消失你知道嗎?在我的回答中,我已經包含了'PDO',因爲如果PHP 5.5出現了,你將會替換你的代碼。現在它已經發布到'PHP 5.5.0 Alpha5中了。如果你的主機有這個PHP版本,你的代碼將不會被執行。只是讓你知道我的朋友:) – Othman 2013-03-04 04:58:07

回答

1

在每次循環迭代中,mysql_insert_id()存儲到一個數組,你可以在以後使用選擇新的記錄。請注意,我用一個整潔foreach這裏免去您的增量for循環:

// Initialize arrays for later 
// one for the new ids 
$inserted_ids = array(); 
// one to keep comments from failed queries 
$failed_comments = array(); 
// and one for the MySQL errors of failed queries 
$errors = array(); 

foreach ($pathway_comment as $comment) { 
    $query = sprintf(
     "INSERT INTO pathway (    
      pathway_pk, 
      case_fk, 
      level, 
      pathway_action_fk, 
      pathway_allowed, 
      comment 
     ) VALUES (
      '', 
      '$case_pk', 
      '1', 
      '$action', 
      '%s', 
      '$comment')", $pathway_allowed === $i ? 'y' : 'n'); 

     $result = mysql_query($query, $connection); 

     // If the iteration was successful, save the insert id onto an array 
     // but only if $pathway_allowed == 'y' 
     if ($result) { 
      if ($pathway_allowed == 'y') { 
       $inserted_ids[] = mysql_insert_id();   
      } 
     } 
     // Otherwise, keep an array of comments that failed 
     // Maybe useful later if you want to print those that failed 
     else { 
      $failed_comments[] = $comment; 
      // And keep the mysql_error() as well. 
      $errors[] = mysql_error(); 
     } 
} 
// Loop is done, now you can implode() the inserted ids array: 
// These are all ints from an auto_increment PK, so no additional escaping needed 
// Execute the query than do whatever you need with the newly inserted rows. 
$query = "SELECT * FROM pathway WHERE pathway_pk IN (" . implode(",", $inserted_ids) . ")"; 

你可能已經聽說過這一點,但從長遠看,考慮切換到支持預處理語句,像庫MySQLi或API PDO。你已經完成了所有必要的轉義和整型轉換,但是如果在循環中編譯並執行預處理語句,除了不需要轉義之外,它可以更快。

+0

很酷,謝謝,我會給它一個去。順便說一句,我問這個問題作爲解決我的問題的可能方式在http://stackoverflow.com/questions/15153196/insert-from-for-loop-add-select-option-value-to-only-one-record – IlludiumPu36 2013-03-04 02:35:41

+0

@PeterBrowne我只是修改了一下 - 沒有注意到你只想保存那些$ pathway_allowed =='y' – 2013-03-04 02:37:14

+0

不是很完美,在插入之後,我想更新插入的四條記錄之一pathway_allowed ='y'... – IlludiumPu36 2013-03-04 02:42:15

1

mysql_connect擴展從PHP 5.5.0開始已棄用,未來將在 中刪除。相反,應該使用MySQLi或PDO_MySQL擴展。 另請參見MySQL:爲更多 信息選擇API指南和相關FAQ。此功能的替代方案包括:PDO和mysqli_connect()

如果您使用的是PDO,則可以使用此功能。

$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); 

,並在for循環,你做這樣的事情:

$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)"); 
$tmt->execute(array('user', '[email protected]')); 
$inserted_ids[] = $dbh->lastInsertId(); 

循環後,你將有4個插入ID的數組

編輯:您不需要重新選擇您輸入您可以使用此

IN FOR LOOP 
{ 
    $stmt = $dbh->prepare($query = sprintf("INSERT INTO pathway (pathway_pk,case_fk,level,pathway_action_fk,pathway_allowed, comment) 
    VALUES (
     '', 
     '$case_pk', 
     '1', 
     '$action', 
     '%s', 
     '$comment')", $pathway_allowed === $i ? 'y' : 'n');); 

     // change the values to bindParam 

    $stmt->execute(array('user', '[email protected]')); 
    $data[$i]['pathway_pk'] = $dbh->lastInsertId(); 
    $data[$i]['case_fk'] = $case_pk; 
    $data[$i]['level'] = 1; 
    $data[$i]['pathway_action_fk'] = $action; 
    $data[$i]['pathway_allowed'] = %s; 
    $data[$i]['comment'] = $comment; 

} 

然後

foreach($data as $d){ 

    echo $d['pathway_pk']; 
    echo $d['case_fk']; 


} 
相關問題