I want to insert a specialty in the “specialties” table and automatically insert it into the other “classesspecialties” table which links the two “classes” and “specialties” tables with the identifier of each table. this table contains the foreign keys of the “classes” table and the “specialties” table.
the tables are:
levels ==> idlev"PRIMARY KEY"
classes ==> idclass"PRIMARY KEY"
specialties ==> idspec"PRIMARY KEY"
levelsclasses ==> idlevclass"PRIMARY KEY"
classesspecialties ==>idclassspec"PRIMARY KEY", idclass"FOREIGN KEY", idspec"FOREIGN KEY"
add_form.php
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<title>ADD Specialty </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<?php
$conn = new mysqli("localhost", "root", "", "database");
mysqli_set_charset($conn,"utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<h2 class="page-title">Try</h2>
<form action="http://localhost/TryWeb/add_Query.php" name="add" enctype="multipart/form-data" method="POST" autocomplete="off">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<?php
$lev=array();
?>
<label>Level</label>
<select class="form-control" name="level" id="level" onchange="$('.sl_class').css('display','none'); $('#level_'+$(this).val()).css('display','');">
<option>Select Level</option>
<?php
$query = "SELECT * FROM levels";
$do = mysqli_query($conn,$query);
while ($row = mysqli_fetch_array($do))
{
$lev[]=$row;
echo'<option value="'.$row['idlev'].'">'.$row['levname'].'</option>';
}
?>
</select>
<br><br>
<label>Class</label>
<?php
for ($i=0;$i<count($lev);$i++)
{
?>
<select class="form-control sl_class" name="class" id="level_<?php echo $lev[$i]['idlev'];?>" style="display:none;">
<option>Select Class</option>
<?php
$query = "SELECT * FROM classes,levelsclasses where classes.idclass=levelsclasses.idclass AND idlev=".$lev[$i]['idlev'];
$do = mysqli_query($conn,$query);
while ($row = mysqli_fetch_array($do))
{
echo'<option value="'.$row['idclass'].'">'.$row['classname'].'</option>';
}
?>
</select>
<?php
}
?>
<br><br>
<label>Specialty </label>
<input type="text" name="specialty" class="form-control" required value="" />
<br><br>
<button type="submit" class="btn btn-lg btn-primary waves-effect waves-light mr-1">Add Specialty</button>
</form>
add_Query.php
<?php
$conn = new mysqli("localhost", "root", "", "database");
mysqli_set_charset($conn,"utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$level = $_POST['level'];
$specialty = $_POST['specialty'];
$sql = "INSERT INTO specialties (idlev,specname)
VALUES('$level','$specialty')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>