我插入多个表,需要从最后一个插入到表1中获取ID,并将其用作表2插入中的变量。
ID会自动递增。
在表单中单击提交按钮后,将运行查询。
查询' S:
$sql = "INSERT INTO table1 (Text) VALUES ($T1text);";
$sql = "INSERT INTO table2 (table1ID,Text) VALUES ($table1id, $T2text);";
table1 {id,Text}
table2 {id,table1.id,Text}
答案 0 :(得分:0)
有一个PHP函数(Decprecated,7.0中删除!) 或者根据mysql / mysqli / pdo函数。
解决方案
PHP(已弃用)
实施例
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
来源:http://php.net/manual/en/function.mysql-insert-id.php
Mysql / Mysqli / PDO
的mysqli $ sql =" INSERT INTO MyGuests(firstname,lastname,email) 价值观(' John',' Doe',' john@example.com')&#34 ;;
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
PDO
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();