select a value in dropdown list from two database tables - php

I want to edit the employees's information in a dropdown list, I have two database tables where there is a shared field :
in table1, I have many fields and one of them is the employee Position which is a number. in table2 I have two fields: EmpPos(which is equal to Position in table1) and PosName.
Now, in the dropdown list, when I add a new employee I fill the list with PosName from table2 but store Position number in table1.
the problem is in the edit form, I print all employee's info from table1 in the form to edit them but I don't know how to select employee's PosName from its associated Position in the dropdown list
here is my code:
echo" <b>Position: </b> <select name='Position' >";
$sql="SELECT * FROM table1 LEFT JOIN table2 ON table1.Position = table2.EmpPos";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$PosName=$row["PosName"];
$Id=$row['EmpPos'];
echo" <option name= '$PosName' value='$PosName' ' . (($Id==$Position) ? 'selected' : '') . '>$PosName</option>";
}
}
thanks

Write query to get all position from position table:
$sql="SELECT * FROM positionTable order by position name asc";
$result = $conn->query($sql);
$Empquery = "Fetch all data related to that employee.";
echo" <b>Position: </b> <select name='Position' >";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$PosName=$row["PosName"];
$Id=$row['EmpPos']; //it must emp's position id fetch from other query.
echo" <option name= '$PosName' value='$PosName' ' . (($Id==$Position) ? 'selected' : '') . '>$PosName</option>";
}
}
echo "</select>";

Related

Changing cell value based on another cell

I am working on a simple php app where I store employees data.
Basically, I have in MySQL few tables, one of them is Employees where I have many columns like name, position, costcenter, manager, etc...
Via php I am able to change the records in the table (simple CRUD).
What I want to achieve is when I change Position based on this Cost Center to be changed.
I have a separate table (CostCenters.sql) with all positions and their cost centers with a structure like this:
CostCenter
Position
124
Engineer
199
Manager
In my edit.php I am taking the positions from this table like this:
echo "<select name='position' required>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT position
from employees
WHERE id = $id
UNION SELECT jobtitle from costcenters");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['position'] ."'>"
.$data['position'] .
"</option>";
}
echo "</select>";`
In the same file for cost centers I have:
echo "<select name='costcenter' required>";
//echo "<option disabled selected>-- Избери --</option>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT costcenter, POSITION
FROM employees
WHERE id = $id
UNION ALL SELECT constcenternr, jobtitle
FROM costcenters ");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['costcenter'] ."'>"
.$data['costcenter'] . "-" .$data['POSITION'] . "
</option>";
}
echo "</select>";`
And my update query is very simple:
UPDATE employees
SET costcenter ='$costcenter',idcard ='$idcard',
personalnr ='$personalnr',position ='$position';
The question is how to make it when I update the record for Position to automatically changed also the CostCenter based on the value corresponding from (CostCenters.sql).
I have tried editing the select query for edit.php to union also the records from (CostCenters.sql) but had no success.
Here is my select query: (simple)
$result = mysqli_query($mysqli,
"SELECT * FROM employees WHERE id ='$id' ");
while($data = mysqli_fetch_array($result))
My first trial was to modify update query in this way:
UPDATE employees
SET costcenter =
(select costcenternr
from CostCenters
where ****),idcard ='$idcard',
personalnr = '$personalnr',position = '$position';
Frankly speaking, my SQL skills are not enough to complete this query

Sending options from html select box into database

Update: I’m now getting an error telling me that roomID is null and this is why it’s not going into the database. Can you see why it would be null when it should be the option that the user selects in the select box?
I'm working on a hotel booking system as an exercise. I am trying to make a form that will insert a new booking into the database. I have the customer and room IDS in the mySQL database and I have put them into HTML select boxes for the user to select an option.
This works fine until I try to save the new booking to the database. I don't get any errors and it tells me the booking has been saved on my page but if I go into the database it hasn't been saved. I have tried inserting the customerID and roomID values from text boxes so just typing it in instead of the drop down menu and that inserts into the database just fine.
I'm pretty sure the problem is something to do with getting the value out of the select box and into the POST variable but I'm not 100% sure. I've only been coding for 6 months so I don't really know what I'm doing! I've tried to figure it out by looking at other examples on here but nothing seems to work.
Here's my code:
Getting the data to fill the select boxes:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
Creating Select boxes:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
Inserting data into database:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}

How to insert into a table after doing a select in a form

I have a PHP form that is collecting information and writing it to a database and it is working correctly. I have one field that is a select to choose entries from an existing table. I would like that result to be inserted into a different table but can't get the insert into to work. I would like to insert the FacilityName field chosen in the select to table2.
$result = mysql_query("SELECT * FROM facility");
print "<select name=\"Id\" > \n";
while ($row = mysql_fetch_array($result)){
$Id = $row['Id'];
$FacilityName = $row['FacilityName'];
print "<option value=$Id>$FacilityName\n";

Echo out results using MySQL queries to query three tables in a table form

I am looking for help. I have 3 tables which I have to query results from. In the table model, I have model_id and model, in the table colour, I have colour_id and colour and in the table availability, I have model_id and colour_id. I have to echo out the results in a table format. The table has to show the model, colour and the availability. In the availability section, if the model is available in a certain colour, it must show/return a yes value and if not show a no. Here is ma current code:
$sql = "SELECT model, colour FROM model, colour";
$query = "SELECT * FROM availability";
$result = mysql_query($sql);
$res =mysql_query($query);
echo "<table border='1'><trbgcolor='#cccccc'><td>Model</td><td>Colour</td><td>Availability</td></tr>";
while($row = mysql_fetch_array($result))
{
$model=$row['model'];
$colour=$row['colour'];
echo "<tr><td>$model</td><td>$colour</td>";
while($row = mysql_fetch_array($res))
{
$avail_id=$row['avail_id'];
$model_id=$row['model_id'];
$colour_id=$row['colour_id'];
}
if($res)
{
echo "<td>Yes</td>";
}
else
{
echo "<td>No</td></tr>";
}
}
echo "</table>";
SELECT m.model, c.colour, IF(c.colour_id IN (SELECT a.colour_id FROM availability a WHERE a.model_id = m.model_id), "YES", "NO") FROM model m, colour c ORDER BY m.model, c.colour
This should give you the results you want. Just format the output to your liking.

Adding Option Group to Query

I am trying to add an Option Group to this select box. I am getting the rows and the count of the number of options in the record set. I can either get the count or set the group. I have yet to do both!
<select name="DETAILS">
<?php
include("config.php");
$sql = "SELECT tblDetails.DetailType AS type, CONCAT(tblDetails.DetailName,' (', Count(tblLocDet.DetailID),')') AS DetailName
FROM tblLocations INNER JOIN (tblLocDet INNER JOIN tblDetails ON tblLocDet.DetailID = tblDetails.DetailID) ON tblLocations.LocationID = tblLocDet.LocationID
GROUP BY tblDetails.DetailType, tblDetails.DetailName, tblLocations.CityID, tblLocations.AreaID, tblLocations.CuisineID
HAVING (((tblLocations.CityID)=16) AND ((tblLocations.AreaID)=131) AND ((tblLocations.CuisineID)=3));";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<optgroup label='{$row['type']}'>";
$DetailNames = explode('|', $row['DetailName']);
foreach($DetailNames as $DetailName) {
echo "<option value='".$DetailName."'>".$DetailName."</option>";
}
echo "</optgroup>";
}
?>
</select>
Help is appreciated.

Categories