保存最后创建的记录ID并在更新查询中使用它的问题PHP

时间:2019-06-13 19:52:09

标签: php mysql

基本上,我在下面的PHP脚本中运行3个查询,导致无法一起工作。

我有一个名为Table1的表,其中包含4个字段(field1field2field3field4

第一个查询应运行并将所提供的值插入到4个字段中的每个字段中,然后是SET @id = last_insert_id;查询,该查询旨在将变量id分配给表中最后插入的id。 / p>

最终查询应更新通过在NUM:(saved value from SET query)中添加field4而创建的相同记录

以下是我目前拥有的,但是我不断收到语法错误:

<?php
$servername = "localhost";
$username = “username”;
$password = “password”;
$dbname = “dbname”;
var_dump( $_POST );

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


$sql = "INSERT INTO Table1 (field1, field2, field3, field4)
VALUES ('TestEntry1’, 'TestEntry2’, 'TestEntry3’, 'TestEntry4’);

$sql = SET @id = last_insert_id;

$sql = UPDATE Table1
    SET field4 = CONCAT(‘NUM:’, <id>)
    WHERE <id> = @id";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

更新:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
var_dump( $_POST );

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 



$sql = "INSERT INTO Equipment (field1, field2, field3, field4)
VALUES ('TestEntry1', 'TestEntry2', 'TestEntry3', 'TestEntry4');";

$sql .= "SET $id = last_insert_id;";

$sql .= "UPDATE Equipment
    SET field5 = CONCAT('NUM', <id>)
    WHERE <id> = $id";

if ($conn->multi_query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

0 个答案:

没有答案