'Dropdown with current value from Mysql
I am struggling to solve a problem in a CRUD working with MySQL (MariaDB). The situation is the following: I have a DB table called "tools" in this table I have a few columns giving information for various production toolings like name, serial number, vendor, etc. I have a CRUD page where I can edit the records, but they are "open text fields" and everyone can wring anything in the textboxes there. I would like to make for example the field "Vendor" to be a dropdown from the database. No problem, I have a table where the possible options are and I am just replacing
<input type="text" name="vendors" value=<?php echo $vendors;?>></td>
with:
<select name="vendors" id="vendors">
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT vendoren, vendorbg From vendors");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['vendoren'] ."'>" .$data['vendorbg'] ."</option>";
}
?> </select>
In this case, I have a dropdown where the user of CRUD can select which vendor to be recorded, but the initial vendor record is no longer visible once you click "edit" in the CRUD interface. I tried a lot of scenarios but I cannot fix them. I guess I will need to modify somehow the query to join the record from table "tools" where the initially selected vendor is recorded.
Additional: I am not a professional programmer and maybe I will need support with the examples. The complete project is as follows: Database: in the database, I have a few tables - vendors - for a list of vendors and tools - this is the "root" table where I am recording the toolings data Add page- I have a page where I am populating data in the "tools" table. Here to prevent free text I am using dropdowns one of them, for example, is "vendors" CRUD page - in this page I can edit, delete, etc records from the "tools" table. The goal is: When I click edit on some record in CRUD the field "Vendor" to be dropdown with the options from the "vendors" table but somehow when you click to edit the record from the "tools" table to be selected by default because the user can edit other fields but not exactly "vendor field".
Solution 1:[1]
Just for information if someone is looking at this topic. The problem is solved:
<select name="vendors" id="vendors" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT vendors FROM tools WHERE id=$id UNION SELECT vendoren FROM vendors");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['vendors'] ."'>" .$data['vendors'] ."</option>";
}
?> </select>
Now the dropdown list is showing currently recorded value and is showing rest of the options from another table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Azim Feta |