How to select an option in php

How to display select option of tag as selected in php

There is a few ways to do this. The easiest way to do this is in fact really simple, you just need to add a keyword “selected” to the option that you want selected.

Method 1 : Simple html select tag to display option as selected in html.

You just need to add an attribute “selected” to the option that you want to be selected. In the below code (Method 1) option samsung with value 2 has been selected.

Method 2 : Display option as selected in php using GET method.

If you are getting any error while executing above code (Method 2) pass query string (URL parameters) in your address bar as ?up_opt=3

Method 3 : Display selecet option as selected in php using foreach method with if statement.

Method 4 : Display selecet option as selected in php using foreach method with ternary operator.

Create an array and iterate it in a foreach loop and make a condition where value of an array is equal to the option value of select for which option you want to be selected. Here the value CAMEROON is used to selected the particular option. You can change or pass dynamic value as per your requirments.

 'AFGHANISTAN', 'BS'=>'BAHAMAS', 'KH'=>'CAMBODIA', 'CM'=>'CAMEROON', 'KY'=>'CAYMAN ISLANDS', 'TD'=>'CHAD', 'CL'=>'CHILE', 'KM'=>'COMOROS', 'CG'=>'CONGO', ); ?>  

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don’t forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.

Источник

PHP Select Option

Summary: in this tutorial, you will learn how to use the element to create a drop-down list and a list box and how to get the selected values from the element in PHP.

A quick introduction to the element

The is an HTML element that provides a list of options. The following shows how to define a element in HTML:

label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)

The element has two important attributes:

  • id – the id associates the element with a element
  • name – the name attribute associates with the value for a form submission.
Читайте также:  Строка php определенные символы

The element nested inside the element defines an option in the menu. Each option has a value attribute. The value attribute stores data submitted to the server when it is selected.

If an option doesn’t have the value attribute, the value attribute defaults to the text inside the element.

To select an option when the page loads for the first time, you can add the selected attribute to the element.

The following example selects the Green option when the page first loads:

label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select>Code language: HTML, XML (xml)

Getting the selected value from a element

We’ll create a form that uses a element.

First, create the following folders and files:

├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.php Code language: JavaScript (javascript)

Second, place the following code in the header.php file:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link rel="stylesheet" href="css/style.css"> title>PHP select option title> head> body class="center"> main>Code language: HTML, XML (xml)

Third, place the following code in the footer.php file:

 main> body> html>Code language: HTML, XML (xml)

Fourth, add the following code to the get.php file to create a form that has one element with a submit button:

form action="" method="post"> div> label for="color">Background Color: label> select name="color" id="color"> option value="">--- Choose a color --- option> option value="red">Red option> option value="green" selected>Green option> option value="blue">Blue option> select> div> div> button type="submit">Select button> div> form>Code language: HTML, XML (xml)

The form uses the POST method to submit data to the webserver.

Finally, add the following code to the post.php file:

 $color = filter_input(INPUT_POST, 'color', FILTER_SANITIZE_STRING); ?>  if ($color) : ?> p>You selected span style="color:"> echo $color ?> span> p> p>a href="index.php">Back to the form a> p>  else : ?> p>You did not select any color p>  endif ?>Code language: HTML, XML (xml)

To get the selected value of the element, you use the $_POST superglobal variable if the form method is POST and $_GET if the form method is GET .

Alternatively, you can use the filter_input() function to sanitize the selected value.

If you select the first option of the element, the selected value will be empty. Otherwise, the selected value is red, green, or blue.

Select with multiple options

To enable multiple selections, you add the multiple attribute to the element:

select name="colors[]" id="colors" multiple> . select>Code language: HTML, XML (xml)

When you select multiple options of a element and submit the form, the name will contain multiple values rather than a single value. To get multiple selected values, you add the square brackets ( []) after the name of element.

Let’s take a look at an example of using a element with multiple selections.

First, create the following folders and files:

. ├── css | └── style.css ├── inc | ├── footer.php | ├── get.php | ├── header.php | └── post.php └── index.phpCode language: JavaScript (javascript)

Second, place the following code into the header.php file:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP Listbox title> link rel="stylesheet" href="css/style.css"> head> body class="center"> main>Code language: HTML, XML (xml)

Third, add the following code to the footer.php file:

 main> body> html>Code language: HTML, XML (xml)

Fourth, include the header.php and footer.php files in the index.php :

 require __DIR__ . '/inc/header.php'; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') < require __DIR__ . '/inc/get.php'; > elseif ($request_method === 'POST') < require __DIR__ . '/inc/post.php'; > require __DIR__ . '/inc/footer.php'; Code language: HTML, XML (xml)

If the HTTP request is GET, the index.php file will show a form from the get.php file. When the form is submitted, the post.php file will handle the form submission.

Fifth, create a form that contains a element with the multiple attribute in the get.php file. The name of the element has an opening and closing square bracket [] so that PHP can create an array that holds the select values.

form action="" method="post"> div> label for="colors">Background Color: label> select name="colors[]" id="colors" multiple> option value="red">Red option> option value="green">Green option> option value="blue">Blue option> option value="purple">Purple option> option value="magenta">Magenta option> option value="cyan">Cyan option> select> div> div> button type="submit">Submit button> div> form>Code language: HTML, XML (xml)

Finally, handle the form submission in the post.php file:

 $selected_colors = filter_input( INPUT_POST, 'colors', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY ); ?>  if ($selected_colors) : ?> p>You selected the following colors: p> ul>  foreach ($selected_colors as $color) : ?> li style="color:"> echo $color ?> li>  endforeach ?> ul> p> p>  else : ?> p>You did not select any color. p>  endif ?> a href="index.php">Back to the form a>Code language: HTML, XML (xml)

The post.php file uses the filter_input() function to get the selected colors as an array. If you select one or more colors, the post.php file will display them.

Summary

  • Use the element to create a dropdown list.
  • Use the multiple attribute to create a list that allows multiple selections.
  • Use $_POST to get the selected value of the select element if the form method is POST (or $_GET if the form method is GET ).
  • Add square brackets( [] ) after the name of the element to get multiple selected values.

Источник

How to select an option in php

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

How to Insert Select Option Value in Database Using PHP & MySQL

In this tutorial, You will learn to insert select option values in the database using PHP & MySQL with some simple steps. These steps are very easy to understand and implement in web applications.

Here, I have taken only a single dropdown input field to store select option values in the database. Once you learn it, you will easily customize it according to your project requirement.

php insert select option in database

How to Store Dropdown Value in Database in PHP

Before getting started it’s coding, you should create the following folder structure –

codingstatus/ |__database.php |__ select-option.php |__ insert-option.php

Learn Also –

Now, let’s start to store dropdown values in the database step by step –

1. Create SQL Database & Table

First of all, You will have to create a database with the name of “codingstatus”.

Database Name – codingstatus

CREATE DATABASE codingstatus;

After that, create a table with the name of “courses” in the database “codingstatus.

CREATE TABLE `courses` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `courseName` varchar(255) DEFAULT NULL, );

2. Connect PHP to MySQL

To insert select option value in the database, you must connect PHP to MySQL database with the help of the following query.

  • $hostName – It must contain hostname.
  • $userName – It must contain username of the database.
  • $password – It must contain password of the database
  • $database – It must contain database name.
connect_error) < die("Connection failed: " . $conn->connect_error); > ?>

3. Create Input Field for Select Option

Here, I have created a single dropdown input field with some select options that contain some course name.

File Name – select-option.php

   

4. Insert Select Option in Database

To insert select option in the database, you will have to implement the following steps to write its code –

Step-1: First of all, apply if condition withisset($_POST[‘submit’]) to check form is set or not

Step-2: Assign course name input to the variable $courseName

Step-3: check course name is empty or not using empty() with if statement. if it is true then follow the next step

Step-4: write MySQL insert query to insert the select option value in the “courses” table

Step-5: if select option is inserted into database successfully then print a success message

File Name – insert-option.php

Insert Select Option Value with another Input Value using PHP & MySQL

Now, You will learn to insert a section option value with another input field like fullName into another table. In the previous step, we have inserted static option values. But In this step, We will display select option values from a database and then insert them into another table of the same database

Before getting started, You will have to create the following two files –

Also, Create another table Name – students with the help of the following query –

CREATE TABLE `students` ( `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `fullName` varchar(255) DEFAULT NULL, `courseName` varchar(255) DEFAULT NULL, );

Create a form and display select option values

First of all, Include database.php and insert-script.php file

Then create an HTML form with a select option & text input field and display data from the database in the select option

Insert Select Option value & Text Input Value

In this step, Write a MySQL query to insert select option value and text input value into the dabase.

File Name – insert-script.php

Источник

Оцените статью