As my title states, I’m trying to dynamically populate a select in html with PHP.
I’ve found some useful code snippets on the internet, but can’t figure out how to connect them together and implement them to my desire.
I have these selects that should get populated, the first one determines what should be put into the second one:
<select id="linetime" name="line" onChange="dynSelect(this.id);">
<option value="L411">L411</option>
<option value="L412">L412</option>
<option value="L414">L414</option>
<option value="L421">L421</option>
<option value="L422A">L422A</option>
<option value="L422B">L422B</option>
<option value="L423">L423</option>
<option value="L424">L424</option>
</select>
<select id="scannertime" name="scanner">
</select>
and tried to populate it this way:
function dynSelect(i){
$.ajax({
type: 'post',
url: "ajax.php.",
data: { id:'i' }
}).done(function(data) {
while(data.length){
$temp = data['scanner'];
$("#scannertime").append($("<options>").text($temp).val($temp));
}
});
}
PHP:
$id = $_REQUEST['id'];
$json = array();
$dsn = "mysql:dbname=faultcounter; host=127.0.0.1";
$user = "root";
$password = "";
$dbh = new PDO($dsn,$user,$password);
$sql = $dbh->prepare("select * from possiblefaults where line=$id");
$sql->execute();
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$json[] = $row;
}
echo json_encode($json);
My problem is, that I am fairly new to script languages and PHP and I don’t quite know how things work as of now, I can’t figure out how to debug properly as I’ve only ever written in C# and Java. I also don’t quite understand if my PHP isn’t returning my desired data or my use of it in the code above is wrong.
I would be glad if someone can explain these things to me.
Note: First time using stackoverflow.
2
Answers
The PHP was flawed in that the prepared statement embedded user supplied data directly in the SQL command and thus negated the benefits of Prepared Statements
As you specifically need the ID to be available to run the sql you should use a logic test to ensure that it is set before proceeding.
The ID attributes of HTML elements could be removed if you were to use another means of selecting the particular select menus – querySelector is really useful for this and as I do not use jQuery I offer a possible solution using vanilla js.
Some slightly modified HTML:
Vanilla js using Fetch
update
The following is exactly as tested – returning results for all items from initial select menu.
The db table data:
you can try this for example:
HTML:
This is the div for your selection
Then next, you’re trying to mix jquery and PHP, but I will give you an example for both
My data in a json file:
jQuery solution:.
PHP solution:
Be aware, for the PHP solution you will need a locally setup database in PhpMyAdmin for example
I hope, this can help you:)