Jump to content

Load mySQL result into select list

Recommended Posts

I am trying to load customer names into a select drop-down list. The first drop down list should result in the second drop down list being updated. However, I am struggling to achieve this, as the list remains empty (only displays Select).

<select class="form-control" id="typelist" name="typelist" onchange="get_namelist()";>
<option value="cases">Case</option>
<option value="processors">Processor</option>

<div id="get_namelist"></div>

<script type="text/javascript">
    function get_namelist() { // Call to ajax function
var typelist = $('#typelist').val();
var dataString = "typelist="+typelist;
    type: "POST",
    url: "mysubselect.php", 
    data: dataString,
    success: function(html)


include "config.php";
if ($_POST){
    $list = $_POST['typelist'];
    echo("<script>console.log('PHP: ".$list."');</script>");
    if ($list != '') {
        $sql = "SELECT name FROM parts WHERE type=" . $list;
        $result = $link->query($sql);
        echo "<select class='form-control' name='partlist'>";
        echo "<option value=''>Select</option>";
        while($row = $result->fetch_assoc())
            echo "<option value='".$row['name']."'>".$row['name']."</option>";
        echo "</select>";
        echo "";

The second list is empty and only outputs Select. What am I doing wrong? Thank you.

Share this post

Link to post
Share on other sites
Posted (edited)

String literals in a query need to be in quotes.


$sql = "SELECT name FROM parts WHERE type='$list' ";

EDIT: You should be using a prepared statement and not putting POSTed data directly into your query.

Edited by Barand

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.