我在MySQL中有3个表:
国家/地区
语言
country_language(具有其他2个表的ID)
我想将WINDOWS 07
和name
插入description
表中,将country
和country id
插入langid
表中。
我该怎么做?
它正在更新部分中运行,但是当我想添加一个新国家时,它并没有在country_language中插入2个ID,只是名称和描述。
country_language
答案 0 :(得分:1)
实际上,在更新过程中,您将获得$ id作为国家ID,并且可能在表country_language
中; country_id
不是NULL,这就是为什么要更新其工作状态
进入代码的插入部分或其他部分,$ id不保存任何内容,并且您也没有将新插入的国家/地区ID的值分配给$id
,因此使代码不起作用
您可以做的只是通过在if条件检查$POST['language']
$id = mysqli_insert_id($connect);
然后使用此$id
插入country_language
表中,它将起作用
答案 1 :(得分:1)
// Using prepared statements you dont need to do this, and its safer
// $name = mysqli_real_escape_string($connect, $_POST["name"]);
// $description = mysqli_real_escape_string($connect, $_POST["description"]);
$id = isset($_POST["country_id"]) ? $_POST["country_id"] : '';
if($id != '') {
// Update query
. . .
$message = 'Data Updated';
} else {
$connect->begin_transaction();
$sql = "INSERT INTO country (name, description)
VALUES(?,?)");
// prepare the query and bind paramters to the ?
$ins = $conect->prepare($sql);
$ins->bind_params('ss', $_POST["name"], $_POST["description"]);
// execute the query
$res = $ins->execute();
// test to see if insert worked
if ( ! $res ) {
// insert failed.
echo $connect->error;
// no rollback required as nothing has been updated anyway
exit;
}
// capture the new id created by above INSERT
$new_ctry_id = $connect->insert_id;
// Using a foreach loop so it will run
// for each occurance in $_POST["language"]
// so only need to check it exists
if(isset($_POST["language"])) {
// prepare the statement outside the loop
// and execute it with new params as many times as you like
$sql = "INSERT INTO country_language
(country_id, language_id) VALUES(?,?)";
$ins2 = $connect->prepare($sql);
foreach($_POST["language"] as $lang) {
// bind the new parameters each time round the loop
$ins2->bind_params('is', $new_ctry_id, $lang);
$res = $ins2->execute();
// test to see if insert worked
if ( ! $res ) {
echo 'Insert of languages failed with ' . $connect->error;
// run rollback to remove the insert of the country
$connect->rollback();
exit;
}
}
}
// if we get here, all is well and we must commit the changes we made
$connect->commit();
$message = 'Data Inserted';
}