dongyue7796
dongyue7796
2017-10-23 04:32
浏览 39
已采纳

如何在angular4中填充mySQL表中的下拉框

In PHP, HTML i just simply used to fetch data in array and show it in the selectbox as shown below -

<?php

mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT nameid FROM PC";
$result = mysql_query($sql);

echo "<select name='PcID'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['nameid'] . "'>" . $row['nameid'] . "</option>";
}
echo "</select>";

?>

I mean i can connects to a MySQL database, issue query, and outputs tags for a box from each row in the table

But how do i achieve same in angular4 ?

The best way is to fetch data in a jsn and then show it on the frontend by creating an API ? or there is some other way ?

Please advise the quick option.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutangliang7769
    doutangliang7769 2017-10-23 04:42
    已采纳

    The best way would be to return the data as a json Using rxjs subscribe you can fetch the data like this

     users:any[]= [];
    fetchData(){
      this.http.get("users/all-users")
          .subscribe((res)=>{
            this.users = res.data
           })
    
      }
    

    So in the html it would be something like

    <select>
        <option *ngFor="let user of users" value="user.id">
      {{ user.name }}
    </option>
    
     </select>
    

    So in your php return data like this

    function getUsers(){
    
      mysql_connect('hostname', 'username', 'password');
       mysql_select_db('database-name');
    
       $sql = "SELECT nameid FROM PC";
       $result = mysql_query($sql);
    
      return ["data"=>$result];
     }
    

    Advice though instead of using normal php use a framework like laravel/yii2 which makes returning data easily

    NB:

    Angular4 is a frontend framework so you cannot using echo like you would use it in a php framework.

    Hope this helps.

    点赞 评论

相关推荐