问题
I've dug through many posts but can't find a scenario quite like this on here...
I have a PHP form that contains a dropdown selection containing option values from a MySQL database table. This part works fine. Here's where I need help...
There is a textarea field that I need to populate with data from the same database table, but a different field. This table contains a 'name' and a corresponding set of 'text'. The dropdown shows the 'name' as the options. So what I need is when a selection is made, a script runs (like onChange)... takes the selected value, queries the database to get the 'text' that is associated with the selected 'name'. That 'text' is then displayed inside of the textarea form field.
A section of this code for you to view is:
echo "<form action=$PHP_SELF method=\"post\">\n";
echo "<select id=\"conditions\" name=\"conditions\">\n";
echo "<option value=\"Select\" selected>Select a Message</option>\n";
$result = mysqli_query($link, "SELECT * FROM db_scripts");
while ($data = mysqli_fetch_object($result)) {
echo "<option value=".$data->script_id.">".$data->script_name."</option>\n";
}
echo "</select>\n";
echo "<br><textarea name=\"message\" style=\"width:300px; height:130px\" data-maxsize=\"160\" data-output=\"status1\" wrap=\"virtual\" maxlength=\"160\"></textarea><br />\n";
So, like I said, this part works just fine. I have the dropdown with the 'script_name' as the options. Now I just need to get the corresponding message into the textarea field "message". Any assistance is most appreciated!
回答1:
Create an associative javascript object literal array in PHP in this format:
<?php
echo "
<!-- this script goes in your <head> -->\n
<script>\n
var db_array = [";
$result = mysqli_query($link, "SELECT * FROM db_scripts");
$first = TRUE; // remove trailing comma from array
while ($data = mysqli_fetch_object($result)) {
if ($first === TRUE) $first = FALSE;
else echo ',';
echo "
{
id: '$data->script_id',
name: '$data->script_name'
message: '$data->script_message'
}";
}
echo "];\n
</script>";
?>
The catch is that if your message is not in the same row as the id, then you need to use JOIN
in your query. The idea behind this part is that you're only querying the database once. You don't want the client to query the database every time they switch an option in the dropdown menu. The exception here is if you have megabytes+ of messages. In this case, consider implementing caching measures.
Moving on... once you have the array constructed, you can build your <option>
s by iterating through the array like so:
<?php
echo "
<form action=\"$PHP_SELF\" method=\"post\">\n
<select id=\"conditions\" name=\"conditions\">\n
<option value=\"Select\" selected>Select a Message</option>\n
<script>\n
for (var i = 0; i < db_array.length; i++) {\n
document.write('<option value=\"'+db_array[i].id+'\">'+db_array[i].name+'</option>');\n
}\n
</script>\n
</select>\n
<!-- notice the id attribute I added -->\n
<br><textarea id=\"message\" name=\"message\" style=\"width:300px; height:130px\" data-maxsize=\"160\" data-output=\"status1\" wrap=\"virtual\" maxlength=\"160\"></textarea><br />\n";
?>
...then have a script with access to these dynamically created DOM elements (e.g. at the end of the <body>
tag)
<script>
// returns the db_array index of the object id supplied
function returnIndex (id) {
for (var i = 0; i < db_array.length; i++) {
if (db_array[i].id === id) return i;
}
return -1; // returns index of -1 if id is not found
}
// changes the <textarea> message. notice the id I added to the messages <textarea> above
function changeMessage (id) {
// remember to handle the case of an id not being found within db_array (where returnIndex returns -1)
document.getElementById('message').innerHTML = db_array[returnIndex(id)].message;
}
// on the event that we switch options, do this event. realize that you'll have to run the changeMessage function once the page loads if you want the first option's message to show
document.getElementById('conditions').onchange = function() {
changeMessage(this.selectedIndex);
}
</script>
回答2:
What you could do is set the form action to GET
.
Then if a conditions
query parameter is set select the corresponding text from the database and show it is the textarea
. So using PDO
s
$text = "";
if(isset($_GET["conditions"])){
$db->prepare("
SELECT text
FROM db_scripts
WHERE script_name = ?
");
$stmt->bindColumn(1, $type);
$stmt->execute();
$row = $stmt->fetch();
if(!empty($row)){
$text = htmlentities($row["text"]);
}
);
echo "</form><textarea name=\"message\" style=\"width:300px; height:130px\" data-maxsize=\"160\" data-output=\"status1\" wrap=\"virtual\" maxlength=\"160\">$text</textarea><br />\n";
回答3:
Ok, I have solved this issue... but ended up NOT using any of the other answers. I tried them, particularly the one from Jared. It got me very close, but in the end, did not fully work. I did get some very helpful direction and ideas from Jared though! In the end though, I found a simpler way to get this done...
1) Pulled JQuery in the <head>
area from Google. No other scripts were loaded there.
2) Put this code in the PHP file above my form, but outside of <?php>
tags.
<script>
$(function () {
$("#conditions").change(function() {
$("#message").val($("#conditions").val());
})
$("#conditions").trigger("change");
})
</script>
3) Setup the dropdown selection field and textarea target field as...
$result = mysqli_query($link, "SELECT * FROM db_scripts");
$first = TRUE; // remove trailing comma from array
while ($data = mysqli_fetch_object($result)) {
$html_opts .= "<option value='".preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($data->script_text))."'>".$data->script_name."</option>";
}
echo '<select id="conditions" name="conditions">';
echo '<option value="" selected>Select a Script</option>';
echo $html_opts.'</select>';
echo '<br><textarea id="message" name="message" style="width:300px; height:130px" data-maxsize="160" data-output="status1" wrap="virtual" maxlength="16\"></textarea><br />';
Of course the entire form is not posted here, but the parts that matter are. This is working perfectly for me now. Hopefully it can help someone else too!
来源:https://stackoverflow.com/questions/19822704/populate-form-text-field-from-database-based-on-dropdown-field-selection