请问我这里有点问题。我写的下面的代码是为了同时插入两个表,但那些不起作用。但如果我删除第二个INSERT,第一个INSERT将工作不知道什么是错的。 IT意味着在第一个表中插入,并将第一个表的最后一个Insert Id收集到第二个表中。我做错了什么
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
$query .= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
答案 0 :(得分:1)
它差不多2018年,所以请停止使用折旧和删除的mysql_*
函数将PDO / mysqli与预处理语句一起使用。
我已使用预先准备好的语句重写您的代码,请点击以下链接:
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "fruitmarket";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = "INSERT INTO data (english_name,tel_number,email_address,gender,age,region) VALUES(?,?,?,?,?,?)";
$sql = $conn->prepare($stmt);
$sql->bind_param("ssssis", $english_name, $tel_number, $email_address, $gender, $age, $region);
if ($sql->execute()) {
$id = $sql->insert_id;
$insert = $conn->prepare("INSERT INTO data_category (id, english_name) VALUES(?,?)");
$insert->bind_param("is", $id, $english_name);
if ($insert->execute()) {
echo "data inserted successfully";
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
预准备语句是用于以高效率重复执行相同(或类似)SQL语句的功能。
准备好的陈述基本上是这样的:
答案 1 :(得分:1)
我测试了上面的代码并注意到你只需要添加和更改一些代码,请参阅下面的示例
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
$query= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
测试它以检查它是否可行