2

我有一个使用 for 循环的多个插入(4 条记录)。然后,我想对在 path_allowed = 'y' 中插入的记录运行更新查询(4 个中只有一个具有此值)。我猜 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...
}
}
4

2 回答 2

1

在每次循环迭代中,将 存储mysql_insert_id()到一个数组中,以后可以使用它来选择新记录。请注意,我在这里for用更整洁的方式替换了您的增量循环foreach

// 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) . ")";

您之前可能听说过,但从长远来看,请考虑切换到支持预准备语句的 API,如 MySQLi 或 PDO。您已经在此处完成了所有必要的转义和整数转换,但是如果在循环中编译和执行准备好的语句会更快,而且不需要转义。

于 2013-03-04T02:27:49.107 回答
1

mysql_connect 扩展自 PHP 5.5.0 起已弃用,将来将被删除。相反,应该使用 MySQLi 或 PDO_MySQL 扩展。另请参阅 MySQL:选择 API 指南和相关的常见问题解答以获取更多信息。此函数的替代方法包括: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', 'user@example.com'));
$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', 'user@example.com'));
    $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'];


}
于 2013-03-04T02:40:18.883 回答