How to add record in two tables with the ID in first table

I want to use the id in one table as value in second table in 2nd query.

When i insert data in first table it save its id in one variable and then use that variable value in 2nd query as value of other column.

i have two tables h_patients and appointments table.

i want that when i insert data in h_patients table on registration.. it adds value in the appointment table too.

i want to use the id of patient (in h_patients table) in patient id column in appointment table.

i tired using $last_id = mysqli_insert_id($conn);

$sql = “INSERT INTO h_patients ( p_name, p_username, p_password, p_email, p_phone, p_disease, department_id, department_name, p_reg_date, appointment_time, p_doctor_id, appointment_status, room_no) VALUES (‘$p_name’,’$p_username’,’$p_password’,’$p_email’,$p_phone,’$p_disease’,$dept_id,’$dept_name’,’$p_reg_date’,’$appointment_time’,$p_doctor_id,’$appointment_status’,$room_no)”;

$result = mysqli_query($conn, $sql) or die(“Query Unsuccessful.”);

if ($result) {
$last_id = mysqli_insert_id($conn);

$sqlIn = ” INSERT INTO appointments( patient_id, patient_name, doctor_id, appointment_status, appointment_time) VALUES ($last_id,’$p_name’,$p_doctor_id,’$appointment_status’,’$appointment_time’)”;

$resultIn = mysqli_query($conn, $sqlIn) or die(“Query Unsuccessful.”);

}