Display data in Select Tag from Database Table and Insert the Selected Value in Different Table

Today I am going to explain you how we display data in Select Tag from the database table and when the user select any value in select tag we have to insert the selected value in another table using PHP code, for doing this you have to just read the below code and do as explain below.

Step1: Create database
           Create database test_db;
           Create Table location;
           Create table location(country char(50),state char(50));
           Insert some data into the table location for testing purpose
           insert into location values('India','Uttar Pardesh');
           insert into location values('India','New Delhi');
           insert into location values('India','MP');
           insert into location values('Saudi Arabia','Jeddah');
           insert into location values('Saudi Arabia','Riyad');
           insert into location values('Saudi Arabia','Jizan');
           Create Table country
           create table country(country_name);
Step2: create a file index.php
            <!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        
       <form method="post" action="add.php">

<?php
 $con = mysqli_connect('localhost','root','root','test_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

   $sql = "SELECT distinct country FROM location";

    $result = mysqli_query($con,$sql);
   
    echo "<select name='select_country'>";
    echo "<option value=''>Select Country:</option>";

      while($row = mysqli_fetch_array($result)){
      echo "<option value='".$row['country']."'>".$row['country']."</option>";
 
        }
        echo  "</select>";
       
        ?>
           <input type="submit" value="Submit"/>

</form>
    </body>
</html>

 Step3: create a file add.php
            <?php
 $con = mysqli_connect('localhost','root','root','test_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$country_name = mysqli_real_escape_string($con, $_POST['select_country']);
$sql = "INSERT INTO country (country_name) VALUES ('$_POST[select_country]')";

    if(mysqli_query($con, $sql)){

        echo "Records added successfully.";

    } else{

        echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);

    }

?>

Output







Note: If you like this code or have any questions then comment me i will solve your problem.

Post a Comment

2 Comments

  1. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. odzyskiwanie danych z uszkodzonego telefonu

    ReplyDelete