mysql - How to insert record which has foregin key referenced to primary key of another table in PHP Script? -
here code-
<?php session_start(); $con = mysqli_connect("localhost", "root", "", "placement") or die("failed connect mysql: " . mysqli_error()); // connecting 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 tbl_country_master countryname='$countryname'"; // insert query $sql = "insert 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);?>
countryid in tbl_state_master foreign key , referenced primary key of tbl_country_master. i'm not able insert data i'm getting error.
you never executed query that's supposed return country id. set $countryid
sql string. should be:
$sql = "select countryid tbl_country_master countryname='$countryname'"; $result = mysqli_query($con, $sql); $row = mysqli_fetch_assoc($result); if ($row) { $countryid = $row['countryid']; }
but ou don't need 2 separate queries, in one:
$sql = "insert tbl_state_master(statename, description, countryid) select '$statename', '$description', countryid tbl_country_master countryname='$countryname'";
Comments
Post a Comment