Get current value from database and and show as selected on edit form page

How do I get the current value from a column in the database table and and show as selected on edit form page in a select dropdown so when I go the edit form it has the value from the db showing in the select dropdown menu

I can’t work out how to do it, I have tried googling it and trying all sorts of ways I have found but nothing has found

the customer_name is what it’s called and being stored in the db table

A shoot in the dark: Do an AJAX call to a REST API server that fetches the data from the SQL server. The API should return JSON to your form.

FWIW

'<option value="'.$value.'" '.($value === $selectedValue ? 'selected="selected"' : '').'>'.$label.'</option>'

Thank you, I added that line in and it just displays the first option in the select dropdown, it needs to show the value as the option from the db table column called customer_name, below is the coding I currently have

<select name="customer_name" class="form-control">
                    <?php
                    $con=mysqli_connect("localhost","username","password","dbname");
                    if (mysqli_connect_errno())
                    {echo "Failed to connect to MySQL: " . mysqli_connect_error();}
                    $sql="SELECT customer_name FROM customers";
                    $result = mysqli_query($con, $sql);
                    while($row = mysqli_fetch_array($result))
                  {    
                    echo '<option value='.$row['customer_name'].($row === $selectedValue ? 'selected="selected"' : '').'>'.$row['customer_name'].'</option>';
                      }
                ?>
                    </select>

In this line

echo '<option value='.$row['customer_name'].($row === $selectedValue ? 'selected="selected"' : '').'>'.$row['customer_name'].'</option>';

you’re comparing the entire $row array to your variable called $selectedValue, so that won’t work - you need to compare the individual array element that you are looking at, I presume that’s $row['customer_name'] here.

Have you set an appropriate value for $selectedValue somewhere that you don’t show in the code above?

Also on that same line of code, and it’s a minor thing, if you’re going to use the same value for the option value as you display, there’s no need to specify it - if there’s no value tag it will automatically be the same as your display text. However in your case, I would suspect you’d want to put the customer unique id field rather than the name so that the customer details can be retrieved on that.

I haven’t set a value for $selectedValue anywhere as not 100% on how to do the code

just set $selectedValue according to the value you want to have selected.

OK, so as we’re comparing the retrieved value to that variable, it’s not going to work even when you compare it to the correct field.

You need to set $selectedValue to the value that you want to be the selected option. So if you’ve retrieved an invoice, for example, and you want this select-tag to default to the customer for that invoice, it needs to be set to the customer name (or id, as I wrote above).

Think I have just solved it with the following coding

if(!empty($_POST) && isset($_POST['client'])) {
    $stmt = $mysqli->prepare("SELECT customer_name FROM customers WHERE customer_name=?");
	$stmt->bind_param("s", $_POST['client']);
					$stmt->execute();
					$stmt->bind_result($customer_name);
					
          if($stmt->fetch() )
          {
           // Send back a jSON array via echo
    echo json_encode(array("data"=>"true","customer_name"=>$customer_name));
    
                
                
             }
				else{

				echo json_encode(array("data"=>"false"));
				}
			 exit;
    
}


$userlist = $mysqli->prepare("SELECT distinct customer_name from customers order by customer_name ASC");
	 /* execute statement */
    $userlist->execute();

    /* bind result variables */
    $userlist->bind_result($customer_name);

    /* fetch values */ 
	
	$userarray=[];
    while ($userlist->fetch()) {
		$userarray[]=array('customer_name'=>$customer_name
	
	);
       
    }
	
    /* close statement */
    $userlist->close();
?>

<script>
$( document ).ready(function() {
    $('#customer_name').editableSelect();
});

</script>

<script>
    $(document).ready(function() {
		
		
        // On change of the dropdown do the ajax
        $("#customer_name").change(function() {
			
			
            $.ajax({
                    // Change the link to the file you are using
                    url: 'add-edit-collection.php',
                    type: 'post',
                    // This just sends the value of the dropdown
                    data: { client: $(".es-list .es-visible.selected").attr('id') },
                    success: function(response) {
						
catch(e){
							
						
						}

}
					
            });
        });
    });
</script>

<select name="customer_name" ng-model="customer_name" id="customer_name" class="form-control">
                    <?php  
	                global $userarray;
	                foreach($userarray as $selection){
                    $selected=(isset($customer_name) && $customer_name == $selection["customer_name"])? "selected" : "";
                    echo '<option '.$selected.' id="'.$selection['customer_name'].'">'.$selection["customer_name"].'</option>';
                    } ?>
                    </select>

That seems quite complex for how I read the original question. How many files is this in, just one, or is the PHP separate?

This line

echo '<option '.$selected.' id="'.$selection['customer_name'].'">'.$selection["customer_name"].'</option>';

seems weird, in that I didn’t think that html option tags had an id attribute. I thought that should be value. As you’re passing the same as you are displaying, it won’t make any difference, other than being invalid (I think) HTML.

it’s just in the one file

What does the Ajax bit do? It seems to call a separate PHP file, but then do nothing with the results.

the add-edit-collection.php is the name of the file that has the select dropdown in, it’s not a seperate file

Still seems a bit strange that you have some Ajax that calls the same page, but then does nothing with the response. Maybe it’s me just not seeing what is happening.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.