如何在PHP脚本中插入具有引用其他表的主键的foregin键的记录?

时间:2015-10-03 00:19:13

标签: php mysql mysqli wamp

这是我的代码 -

<?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的主键。由于我收到错误,我无法插入数据。

1 个答案:

答案 0 :(得分:0)

您从未执行过应该返回国家/地区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'";