PHP / mysql,使用外键通过从表单接受(名称)来插入(id)

I have 2 tables, one called school and one called student. Inside student I have several columns, one being a foreign key of school_Id. I also have several columns in school table(i.e. school_Id, name,...). I accept 'name' of the school from form. i want to insert the 'school_Id' in student table.

To select 'school_Id' I use....(*$schno - is the accepted 'name' from form)

$sno="SELECT  school_Id FROM school where Name='$schno' ";

$resno = mysql_query($sno) or die("query error".mysql_error());

To insert the value to student table I use:

$sql="insert into  student values('$no','$fname','$mname','$lname','$bdate','$age','$sex','$batch','$year','$manam','$mafnam','$resno')";
$res=mysql_query($sql) or die("query error".mysql_error());

                    ..but it isn't working.
  1. You must fetch the data after you run mysql_query function:

    $sql="SELECT school_Id FROM school where Name='$schno' ";

    $result = mysql_query($sql) or die("query error".mysql_error());

    $resno = mysql_fetch_field($result, 0);

  2. If it's an integer, don't use quotes in INSERT query: : '$resno' -> ,$resno.

  3. Please, quote your variables with mysql_​real_​escape_​string before using them in query.

  4. Consider switching to PDO or mysqli as mysql lib is deprecated.