Php:获取mysql表上最后插入的行,用于另一个mysql语句


Php: fetching last inserted row on mysql table to use for another mysql statement

我需要使用php从mysql表中获取最后插入行的id,并使用该id在另一个表中输入新条目。我有这个直到现在

$inductionmethod = $_POST['inductionmethod'];   
$injectionmethod = $_POST['injectionmethod'];   
$dosage = $_POST['dosage'];     
$metric = $_POST['metric'];     
$notes = $_POST['notes'];       
global $db_usr;     
$query = "SELECT MAX( experiment_id ) FROM experiment";     
$prep = $db_usr->prepare($query);   
$lastid = $prep->fetch();
$query ="INSERT INTO experiment_using_methods (experiment_id, induction_method, injection_method, dosage_quantity, dosage_unit, dosage_qualitative)
        VALUES (
        '".$lastid['MAX( experiment_id )']."', # the fetched ID of the corresponding dataset
        (SELECT induction_method_id FROM induction_method WHERE im_name = '".$inductionmethod."'), # name of induction method
        (SELECT injection_method_id FROM injection_method WHERE im_name = '".$injectionmethod."'), # name of the injection method
        '".floatval($dosage)."', # dosage quantity
        '".$metric."', # dosage unit or metric
        '".$notes."' # qualitative dosage - REMOVE??
        )";
$prep = $db_usr->prepare($query);       
$prep->execute();

我想我在获取MAX(experiment_id)时遇到了错误,或者我在INSERT语句中使用错误,因为如果我用数字替换".$lastid['MAX(expection_id)']"部分,INSERT语句就可以正常工作。另一方面,我还在mysql命令行上测试了SELECT MAX(experiment_id)FROM实验语句,它也运行良好。我是否正确地使用了获取和引用结果值?

这是主要问题:

$prep = $db_usr->prepare($query);   
$lastid = $prep->fetch();

将其更改为:

$prep = $db_usr->prepare($query);   
$prep->execute();
$lastid = $prep->fetch();

如果连接为$con,那么对于MySQLi面向对象:

if ($con->query($sql) === TRUE) {
    $last_id = $conn->insert_id; 
}

MySQLi过程方式:

if (mysqli_query($con, $sql)) {
    $last_id = mysqli_insert_id($con);
}

PDO方式:

$con->exec($sql);
$last_id = $con->lastInsertId();