Creating database for showing items in Dynamic Selectbox is too easy but took much time to complete the proper process of Creating, Updating, Deleting, Positioning the data. We have to create almost 2 3 extra pages for a single dropdown.
If i tell you that you can eliminate this process and achieve the same result in less time and with less code. I am sure if you read this small tutorial you can also do it. For creating dynamic selectbox dropdown we will use Text File not the database.
Things we need
- Text File
- SelectBox Items
- 5 Mins
First of all we will create a text file for our dropdown values. Please keep in mind that you have to enter the data in the separate lines eveytime. One Data One Line
Example we will create a car brand name text file –
Toyota Maruti Isuzu Mahindra Renault BMW Audi Tata Others
As you can see we have crated a list of brand names and you have to add them in text file as they are looking here.
Now we will use this text file in our PHP Code by using the file_get_contents() method. After getting all the data we will create the array of the received data and put that data in Dropdown using the foreach loop.
<select class="form-control input-sm" id="Cars" name="Cars"> <?php $getSourceFile= file_get_contents("cars.txt"); $sourceArr=explode("\n", $getSourceFile); if(count($sourceArr)){ foreach ($sourceArr as $value) { echo '<option value="'.$value.'">'.$value.'</option>'; } } ?> </select>
As you can see i have created a very short and simple code for getting the Data in Select box. Now will create a PHP page which will show the textfile data in that file we can update the data according to our need.
Manage-textfile.php
<?php if(isset($_POST["add"])){ $file_path="extra/sources.txt"; $datatoWrite= trim($_POST["text"]); file_put_contents($file_path, $datatoWrite); } ?>
Above code will work on the button click and it will update the details of the text file. Now by using the textarea we can see the added text.
<?php $getSourceFile= file_get_contents("cars.txt"); ?> <form class="" autocomplete="off" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post"> <textarea rows="15" class="form-control" id="text" name="text"> <?php echo $getSourceFile; ?> </textarea> <div class="row xs-pt-15"> <div class="col-xs-6"> <p class="text-right"> <button type="submit" id="add" name="add" >Update Details</button> </p> </div> </div> </form>
Thank you for reading the Dynamic Selectbox tutorial. Hope you like the tutorial please share it with others . You can download the files from the bottom of the article.