This topic is locked

Custom PHP Dropdown - Get user selected value and option

2/6/2025 10:12:56 PM
PHPRunner General questions
C
chandoshi authorDevClub member

I have a custom PHP dropdown programed as a code snippet. it display multiple columns from a single database records as rows of items to select from. The code works perfectly.
How do I save the user selected value and option in Session variable?


$str = "<select style='width: 150px; display: inline-block;' class='form-control' onchange=\'window.location.href=this.options[this.selectedIndex].value;\'>";
//select values from the database
$strSQL = "SELECT idPM, namePM, idRM, nameRM, idSP1, nameSP1, idSP2, nameSP2, idAJ1, nameAJ1, idAJ2, nameAJ2, idRFC, nameRFC
FROM JobLinkIndividuals where pkJobsId = ".$_SESSION['luJobId'];
$rs = db_query($strSQL);
//echo "<script type='text/javascript'>alert('$strSQL');</script>";
while ($data = db_fetch_array($rs)) {
$str.="<option value=''>-Select Contact-</option>";
if($data["namePM"]!="") $str.="<option value=".$data["idPM"].">".$data["namePM"]."</option>";
if($data["nameRM"]!="") $str.="<option value=".$data["idRM"].">".$data["nameRM"]."</option>";
if($data["nameSP1"]!="") $str.="<option value=".$data["idSP1"].">".$data["nameSP1"]."</option>";
if($data["nameSP2"]!="") $str.="<option value=".$data["idSP2"].">".$data["nameSP2"]."</option>";
if($data["nameAJ1"]!="")$str.="<option value=".$data["idAJ1"].">".$data["nameAJ1"]."</option>";
if($data["namAJ2"]!="") $str.="<option value=".$data["idAJ2"].">".$data["nameAJ2"]."</option>";
if($data["nameRFC"]!="") $str.="<option value=".$data["idRFC"].">".$data["nameRFC"]."</option>";
echo $str;
}


C
copper21 2/7/2025

Use ChatGPT:

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['contactSelect'])) {
$_SESSION['selected_contact'] = $_POST['contactSelect']; // Store in session
}

// Generate dropdown
$str = "<form method='POST' action=''>"; // Add a form wrapper
$str .= "<select name='contactSelect' style='width: 150px; display: inline-block;' class='form-control' onchange='this.form.submit();'>";
$str .= "<option value=''>-Select Contact-</option>";

// Select values from the database
$strSQL = "SELECT idPM, namePM, idRM, nameRM, idSP1, nameSP1, idSP2, nameSP2, idAJ1, nameAJ1, idAJ2, nameAJ2, idRFC, nameRFC
FROM JobLinkIndividuals WHERE pkJobsId = " . $_SESSION['luJobId'];
$rs = db_query($strSQL);

while ($data = db_fetch_array($rs)) {
if ($data["namePM"] != "") $str .= "<option value='" . $data["idPM"] . "'>" . $data["namePM"] . "</option>";
if ($data["nameRM"] != "") $str .= "<option value='" . $data["idRM"] . "'>" . $data["nameRM"] . "</option>";
if ($data["nameSP1"] != "") $str .= "<option value='" . $data["idSP1"] . "'>" . $data["nameSP1"] . "</option>";
if ($data["nameSP2"] != "") $str .= "<option value='" . $data["idSP2"] . "'>" . $data["nameSP2"] . "</option>";
if ($data["nameAJ1"] != "") $str .= "<option value='" . $data["idAJ1"] . "'>" . $data["nameAJ1"] . "</option>";
if ($data["nameAJ2"] != "") $str .= "<option value='" . $data["idAJ2"] . "'>" . $data["nameAJ2"] . "</option>";
if ($data["nameRFC"] != "") $str .= "<option value='" . $data["idRFC"] . "'>" . $data["nameRFC"] . "</option>";
}

$str .= "</select>";
$str .= "</form>"; // Close the form
echo $str;

// Display the selected contact for verification
if (isset($_SESSION['selected_contact'])) {
echo "Selected Contact ID: " . $_SESSION['selected_contact'] . "
";
}

You can take the last part out to display it if you want...but you should be able to use the session variable "$_SESSION['selected_contact']" in your app.

C
chandoshi authorDevClub member 2/9/2025

Thanks for getting back to me. The solution work perfectly. Just 2 questions for clarification.

  1. Why is the [ if $_SERVER["REQUESTMETHOD"] == "POST "] statement call before the [echo $str;] ?
  2. How can I also get the name slected along with the id?*

C
copper21 2/10/2025

According to Chat GPT, the reason why the [ if $SERVER["REQUESTMETHOD"] == "POST "] is before the dropdown is because you want to capture and process the submitted form data before rending and updating the dropdown.

Now to get the name selected along with the ID, do you want the ID to show in the dropdown too?

Peer Plaut 2/10/2025

copper21 -
Did you use chat gpt to generate the code or to find similar code on XlineSoft documentation?
~P.

fhumanes 2/11/2025

Hello,
In a development that I just finished and that I will publish proximly, which I think you are asking.

In my problem, I need to facilitate a selector field with all the backup files in a directory and the user has to select one, to apply it to recovery.

In this case, the field information is not even based on the database.

What have I done:

1.- I define a view of one of the tables of the application that what serves me is for Phprunner to facilitate the access insurance issues and the "frame" of the application, the rest of the fields, I eliminate it in the Design page

2.- Defined a "snippet", to build the HTML that I need for the selector field, and access the directory to collect the files that exists and puts it as values ​​of it.

3.- I define a 3-states button, where:

  • (JavaScript) I collect the data of the selector field and pass it to the parameter structure. I also show a GIF, to inform that the operation is being done.
  • (PHP), I collect the value of the Páralectro and I do the option operation. I send the result of the operation
  • (JavaScript). You notify how the process has gone.

The codes are:

  • Snippet

<?php

$option='';

// Recoger los ficheros de export de base de datos, más recientes.| Leave only the 5 recent database export.

$pref_filebackup = 'Videoclub';

chdir(DIR.'/backup_files/');

$arrFiles = glob($pref_file_backup.'*');

rsort($arrFiles); // Ordenar de mayor a menor

for ($i = 0; $i < count($arrFiles); $i++) {
$option .= "<option>".$arrFiles[$i]."</option>\n";
}

$html = <<< EOT
<div class="form-group">
<label class="r-edit-label control-label" for="value_file_1">
Seleccione el fichero para la Recuperación
<span class="icon-required"></span>
</label>
<select class="form-control" id="selection_file">
$option
</select>
</div>
EOT;
echo $html;

  • Before Javascript

// Put your code here.
params["file_restore"] = $("#selection_file").val(); // Recoje el fichero del Selector de fichros

console.log('Fichero de carga: ',params["file_restore"]);
Swal.fire({
// icon: 'info',
title: 'El Restore se ha iniciado se ha inciado y se está ejecutando',
text: '',
imageUrl: "backup/images/calculated.gif",
imageHeight: 200,
imageAlt: "Estamos trabajando",
timer: 60000,
timerProgressBar: true,
toast: true,
showConfirmButton: false,
position: 'center', // "top-start",
footer: ''
})

return true;

  • Server

$file_restore = $params["file_restore"]; // Fichero del backup

include "backup/restore.php";

$result["message_user"] = $message_user;

- After Javascript

console.log('Inicia la 3 fase');
var msg_user = result['message_user'];

if (confirm("El mensaje del Restore es: " + msg_user) == true) {
window.open("menu.php", "_self");
} else {
window.open("menu.php", "_self");
}

img alt

Greetings,
fernando