简体   繁体   English

如何使用嵌套 SELECT 获取 INSERT 查询的插入行数? 没有受影响的行,结果 ID,数量行

[英]How do I get a count on inserted rows for INSERT query with nested SELECT? No luck with affected_rows, result_id, num_rows

The INSERT statement with SELECT in VALUES:在 VALUES 中带有 SELECT 的 INSERT 语句:

$stmt = $db->prepare("INSERT INTO weld_reference(weld_id,report_id) VALUES ((SELECT w.id FROM welds w WHERE w.weld_number=?),?)")

The below code loops through an array of user submited strings ($welds) and tries insert its ID into table weld_reference if it exists in table welds .在下面的代码循环通过的用户的阵列submited字符串($焊缝)和尝试插入其ID到表weld_reference如果在表中存在welds

    $stmt->bind_param("si",$weld_number,$_POST['report_id']);
    foreach($welds as $weld_number){
        if($stmt->execute() and $stmt->num_rows){
            ++$insert_count;
        }
    }   

I don't want to do another query to see if the row exists, I was hoping that I could get the number of rows or success of the INSERT after each $stmt->execute().我不想再做一次查询来查看该行是否存在,我希望在每次 $stmt->execute() 之后都能获得行数或 INSERT 的成功。

However, $stmt->affected_rows , and $stmt->insert_id always returns 1 and $stmt->num_rows always returns 0 whether a row was inserted or not.然而, $stmt->affected_rows$stmt->insert_id总是返回 1 而$stmt->num_rows总是返回0无论是否插入了一行。

How can I get a read on this and see if a row has been inserted to send an accurate feedback message to the user?我如何才能阅读此内容并查看是否已插入一行以向用户发送准确的反馈消息?

How do you check the value of $stmt->insert_id ?你如何检查$stmt->insert_id的值? Because it should return you "Get the ID generated from the previous INSERT operation".因为它应该返回“获取从前一个 INSERT 操作生成的 ID”。 If ou only ($evaluate) it it will return true (as 1)如果 ou only ($evaluate) 它将返回 true (as 1)

The way i do it is i store the id's in an array so i can have a nice list of what has been inserted.我这样做的方式是将 id 存储在一个数组中,这样我就可以有一个很好的插入内容列表。

$stmt->bind_param("si",$weld_number,$_POST['report_id']);
    foreach($welds as $weld_number){
        if($stmt->execute()){
          $insertedId[]=$stmt->insert_id;
        }
    } 
echo count($insertedId);

Or since an id would logicaly never be empty you could do或者因为 id 逻辑上永远不会为空,你可以这样做

$stmt->bind_param("si",$weld_number,$_POST['report_id']);
    foreach($welds as $weld_number){
        if($stmt->execute() && !empty($stmt->insert_id)){
            $insert_count++;
           // ++$insert_count; //unaware of this syntax -.-
        }
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM