因此,我将表company定义如下:
CREATE TABLE IF NOT EXISTS chkdcrm.company (
company_id INT(11) NOT NULL AUTO_INCREMENT,
name_de VARCHAR(150) NOT NULL,
parent_company INT(11) NULL,
PRIMARY KEY (company_id),
CONSTRAINT parent_company
FOREIGN KEY (parent_company)
REFERENCES chkdcrm.company (company_id)
ON DELETE SET NULL)
ENGINE = InnoDB;
对于html表单:
<?php
$require_once '../conn.php';
//...
$parent_company="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
//codes...
if ($_POST["parent_company"] == '') {
$parent_company = 'NULL';
}
else {
$parent_company = $_POST["parent_company"];
}
$sql = "INSERT INTO company (name_de, parent_company) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, 'si', $param_name, $param_parent);
$param_name = $name_de;
$param_parent = $parent_company;
mysqli_stmt_execute($stmt) or die(mysqli_error($conn));
$company_id = mysqli_insert_id($conn);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
//html表单。。。
<div class="form-group">
<label>Parent company(if exists)</label>
<br>
<?php
echo '<select name="parent_company">';
echo '<option value=""></option>';
$result = mysqli_query($conn, "SELECT company_id, name_de FROM company ORDER BY name_de ASC");
while ($row = mysqli_fetch_assoc($result)){
echo '<option value = "'.$row['company_id'].'">'.$row['name_de'].'</option>';
}
echo '</select>';
?>
</div>
目标是从查找字段中选择父公司。但我不知道如何插入没有母公司的公司(即父公司=null)。我收到错误消息: Cannot add or update a child row: a foreign key constraint fails (chkdcrm.company, CONSTRAINT parent_company FOREIGN KEY (parent_company) REFERENCES company (company_id) ON DELETE SET NULL)
.
我认为问题在于,由于company\u id是int,所以它不接受null值。因此,它被视为无效的插入。但我怎么才能避开这个问题呢?有人能帮我吗?
暂无答案!
目前还没有任何答案,快来回答吧!