Skip to content
Advertisement

How to submit table form to a selected table in database based on drop down selection

may I know is it possible for submit a table form to a selected table in mysqli database based on drop down selection ?

For an example, user can select which table A or B in a mysqli database using the drop down selection and click send. Below code is just an example (but my exact code)

Requesting for the resolution. Thank you.

<form  method="post" action="">
    <table name="userform" >
        <tr><th>Full Name</th>
            <th>  Week  </th></tr>
        <tr><td><input name="name" type="text" id="name"></td>
            <td><input name="week" type="number" id="week"></td></tr>
    </table>
     <select name="sendToWho" >
     <option value="tableA" >table A</option>
     <option value="tableB" >table B</option>
     <option value="tableC">table C</option>
     <input type="submit" name="save" id="save" value="Save Data">
</form>

I used ‘”.$name[$tableName].”‘ because it is a add,delete,editable table before send to the mysqli database,

<?php
$conn = mysqli_connect("localhost","root","","mySystem");
$sendTO = [
    "tableA" => "optionA",
    "tableB" => "optionB",
    "tableC" => "optionC",
          ];

foreach ($sendTO as $tableName => $optionName)
 {    
        $table = isset($_POST["userform"], $sendTO[$_POST["name"]])
                 ? $sendTO[$_POST["week"]]
                : $sendTO[0];

        $sql = "INSERT INTO `$table`(Name, Week) VALUES ('".$name[$tableName]."','".$week[$tableName]."')";
        $query = mysqli_query($conn,$sql);
}
?>  

Advertisement

Answer

Not entirely sure of what you are trying to achieve, but something like this could work:

$conn = mysqli_connect("localhost","root","","mySystem");

if (isset ($_POST['save'])){

$name = $_POST['name'];
$week = $_POST['week'];
$sendTo = $_POST['sendToWho'];

//check which option was selected and delegate the correct table accordingly
switch ($sendTo){

case 'tableA':      
$stmt = $conn->prepare('INSERT INTO optionA (Name, Week) VALUES (?,?)');
break;

case 'tableB':
$stmt = $conn->prepare('INSERT INTO optionB (Name, Week) VALUES (?,?)');
break;

case 'tableC':
$stmt = $conn->prepare('INSERT INTO optionC (Name, Week) VALUES (?,?)');
break;

default:
echo "error";        
break;       

}
    
$stmt->bind_param('ss', $name, $week); // see www.php.net/manual/en/mysqli-stmt.bind-param.php 
$stmt->execute();

}    
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement