简体   繁体   中英

Get the data from database and put it in an select list

I am doing an update using JavaScript and HTML. I want to put the values in a drop down list. But I am not able to loop all the other data into the dropdown. I want to create a HTML drop down menu in it with all the values so that I can select other options from the drop down menu. I am getting the previous values from the db. How can I get the remaining categories as well in the options?

Controller

public function productlist($product_id)
{
    $this->load->model('Productmodel');
    $response=array();
    $response = $this->Productmodel->getproductlistbyid($product_id);
    echo json_encode($response);
}

Model

public function getproductlistbyid($product_id)
{
    $returnarray = array();

    $sql = "select id, product_name, image,  b.name as bname, c.name as cname, a.category_id as acategory_id, a.subcat_id as asubcat_id, description, qty, color, orginal_price, offer_price from tbl_product as a inner JOIN category as b on a.category_id = b.category_id inner JOIN category as c on a.category_id = c.fk_parent_id where id = ?";

    $query = $this->db->query($sql, array($product_id));

    if($query->num_rows())
    {
        $rows = $query->result();

        foreach($rows as $temp)
        {
            $returnarray[0] = $temp->id;
            $returnarray[1] = $temp->product_name;
            $returnarray[2] = $temp->image;
            $returnarray[3] = $temp->bname;
            $returnarray[4] = $temp->cname;
            $returnarray[5] = $temp->description;
            $returnarray[6] = $temp->qty;
            $returnarray[7] = $temp->color;
            $returnarray[8] = $temp->orginal_price;
            $returnarray[9] = $temp->offer_price;
            $returnarray[10] = $temp->acategory_id;
            $returnarray[11] = $temp->asubcat_id;
        }

    }

    return $returnarray;

}

View (Script)

 <script>
 function editproduct(product_id)
 {
 var myurl="<?php echo base_url();?>index.php?/Product/productlist/"+product_id;

//alert(myurl);

  $.post(myurl).done(function (data)
  {
     //alert(data);

      var obj=jQuery.parseJSON(data);
    //alert(obj);

      //alert(myhtml);
      var myhtml='<form role="form" id="formedit" action="#">'+
                 '<div class="box-body">'+
                 '  <div class="form-group">'+
                 '  <label for="exampleInputName">Product Name</label>'+
                 '  <input type="hidden"  id="upmyid" name="editid" value="'+obj[0]+'">'+
                 '  <input type="text" class="form-control" id="upname" placeholder="Product Name" name="editpname" value="'+obj[1]+'">'+
                 '  </div>'+
                 '</div>'+
       '<div class="box-body">'+
       '<div class="form-group">'+
       '<label for="exampleInputImage">Image</label>'+
       '<input type="file" class="form-control" id="upimage" placeholder="Image" name="editpimage" value="'+obj[2]+'">'+
       '</div>'+
       '</div>'+
       '<div class="box-body">'+
       '<div class="form-group">'+
       '<label for="exampleInputCategory">Category</label>'+
       '<select class="form-control select category" style="width: 100%;" name="option2" id="option2">'+
       '<option value="0">Main Menu </option>'+
       '<option value="'+obj[9]+'" selected>'+obj[3]+'</option>'+
       '</div>'+
       '</div>'+
                 '</form>';

                 swal({ title: "Edit <small>this</small>!",
                        text: myhtml,
                        html: true,
                        type: "",   showCancelButton: true,   confirmButtonColor: "#3c8dbc",
                        confirmButtonText: "Update Now",
                        closeOnConfirm: false },
                        function()
                        { 
                            var id=$('#upmyid').val();
                            var name=encodeURIComponent($('#upname').val());
                            var myurl="index.php/Product/updateProduct/"+id+"/"+name;

                            $.post(myurl).done(function(data)
                            {
                                //alert(data);

                                var obj = jQuery.parseJSON(data);

                                //alert(obj);

                                if(obj[0]==100)
                                {

                                    swal({      title: "Updated Successfully",
                                    text: "Click on ok now!",
                                    type: "success",   showCancelButton: false,   confirmButtonColor: "#3c8dbc",
                                    confirmButtonText: "OK",
                                    closeOnConfirm: false },

                                    function()
                                    { 
                                        location.reload(); 
                                    });
                                }

                                else
                                {
                                    swal("Sorry!",
                                    "Unable to Update now.",
                                    "warning");
                                }

                            });

                        }
                    );
  });
  }
  </script>  

Every time you run your foreach row in PHP it over-writes the same portions of the array with the latest values. eg if you have 10 rows returned from your DB, then the loop runs 10 times. Therefore $mainarray[0] is replaced 10 times with the latest value of $temp->id; , and the same for all the other fields. This means you'll only ever get the values from the last DB row into your PHP array.

Try it like this (untested, apologies for any minor errors):

Model:

    foreach($rows as $temp)
    {
        $returnarray[] = $temp;
    }

This will place the whole $temp object into the next available index of $mainarray .

Secondly, your JavaScript code is not set up to deal with multiple items in the response, and therefore will only ever print one data item, even if many items were to be returned.

View

1) Remove this line:

  var obj=jQuery.parseJSON(data);

There should be no need for this - $json_encode() in your PHP will already be returning a JSON object, not a string, so you don't need to parse it. jQuery will understand data to be a JSON object already.

2) Update your HTML generating code like this (the changes are where it renders the <select> ). It needs to loop through the data array and create one <option> for each object in the array.

      var myhtml='<form role="form" id="formedit" action="#">'+
             '<div class="box-body">'+
             '  <div class="form-group">'+
             '  <label for="exampleInputName">Product Name</label>'+
             '  <input type="hidden"  id="upmyid" name="editid" value="'+obj[0]+'">'+
             '  <input type="text" class="form-control" id="upname" placeholder="Product Name" name="editpname" value="'+obj[1]+'">'+
             '  </div>'+
             '</div>'+
   '<div class="box-body">'+
   '<div class="form-group">'+
   '<label for="exampleInputImage">Image</label>'+
   '<input type="file" class="form-control" id="upimage" placeholder="Image" name="editpimage" value="'+obj[2]+'">'+
   '</div>'+
   '</div>'+
   '<div class="box-body">'+
   '<div class="form-group">'+
   '<label for="exampleInputCategory">Category</label>'+
   '<select class="form-control select category" style="width: 100%;" name="option2" id="option2">' +
   '<option value="0">Main Menu </option>';
$.each(data, function(index, obj) {
  myhtml += '<option value="' + obj.acategory_id + '">' + obj.cname + '</option>';
});
 myhtml += '</select>' +
   '</div>'+
   '</div>'+
'</form>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM