返回要在下一个execute()语句中使用的行ID#?

问题描述 投票:0回答:1

为一些本应非常简单的事情而苦苦挣扎。我有三个表,一个用于工厂读数的主表,其 id 是关联来自压缩机表和冰温表的多个读数的外键。我想在创建后从工厂读取中获取 id,以在将数据插入压缩机和冰表时用作外键。但代码在 $plant_check_id 周围中断。我不明白为什么? lastInsertId() 似乎也不起作用?

创建新的植物读数时,第一步是创建具有唯一 ID 的新记录

        //create a new plant reading
        $new_plant_reading = $connection->prepare("
            INSERT INTO plant_readings (time_of_day) VALUES (:time_of_day)");

        $plant_reading = $new_plant_reading->execute(
                array(
                ':time_of_day' => $_POST["time_of_day"]
                )
            ); 

        $last_id = $connection->prepare("
            SELECT MAX(id) FROM `plant_readings`");
        $plant_check_id = $last_id->query();  
        //$plant_reading_id = intval($plant_check_id->lastInsertId());

        $statement = $connection->prepare("
            INSERT INTO compressor_readings (suction, discharge, oil_pressure, oil_temperature, water_temperature, compressor_id, plant_readings_id) VALUES (:s, :d, :op, :ot, :wt, :cid, :pid)");
        $result = $statement->execute(
            array(
                ':s'    =>   $_POST["suction1"],
                ':d'    =>   $_POST["discharge1"],
                ':op'    =>   $_POST["oil_pressure1"],
                ':ot'    =>   $_POST["oil_temperature1"],
                ':wt'    =>   $_POST["water_temperature1"],
                ':cid'    =>   1,
                ':pid' => $plant_check_id 
            )
        );

提前致谢

php mysql pdo last-insert-id
1个回答
0
投票

您应该使用

lastInsertId
函数,因为如果您有多个写入者更新表,从表中选择
max(id)
将无法正常工作 - 您无法确定
id
读取是否属于您插入的行。

对于 MySQL

lastInsertId
返回最后一个插入 在连接上,因此只要您在另一个插入之前执行此操作,您就会得到正确的
id
,即使在您的插入之后发生了其他插入。

它可能不适合您,因为您是在查询上调用它,而不是在刚刚执行插入的连接上调用它。

尝试一下,看看是否得到一个值:

$new_plant_reading->execute( ... );
$lastId = $new_plant_reading->lastInsertId(); // use the connection
© www.soinside.com 2019 - 2024. All rights reserved.