如何在 PHP 脚本中插入对另一个 table 的主键有外键引用的记录?

How to insert record which has foregin key referenced to primary key of another table in PHP Script?

这是我的代码-

<?php
    session_start();
    $con = mysqli_connect("localhost", "root", "", "placement") 
    or die("Failed to connect MySQL: " . mysqli_error()); // Connecting to MySQL Database

    // Variable Declaration
    $StateName = mysqli_real_escape_string($con, $_POST["txtStateName"]);
    $Description = mysqli_real_escape_string($con, $_POST["txtDescription"]);
    $CountryName = mysqli_real_escape_string($con, $_POST["selectCountryName"]);
    $CountryId = "SELECT CountryId FROM tbl_country_master WHERE CountryName='$CountryName'";

    // Insert Query
    $sql = "INSERT INTO tbl_state_master(StateName, Description, CountryId) VALUES ('$StateName', '$Description', '$CountryId')";

    if(!mysqli_query($con, $sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    else
    {
        header("Location: frmAddState.php?msg=1");
    }

    mysqli_close($con);?>

tbl_state_master 中的 CountryId 是一个外键,它引用了 tbl_country_master 的主键。我无法插入数据,因为出现错误。

您从未执行过本应 return 国家/地区 ID 的查询。您只需将 $CountryId 设置为 SQL 字符串。应该是:

$sql = "SELECT CountryId FROM tbl_country_master WHERE CountryName='$CountryName'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
    $CountryId = $row['CountryId'];
}

但您不需要两个单独的查询,一次即可完成:

$sql = "INSERT INTO tbl_state_master(StateName, Description, CountryId)
        SELECT '$StateName', '$Description', CountryId
        FROM tbl_country_master WHERE CountryName='$CountryName'";