简体   繁体   中英

How to populate a drop-down box from a MySQL table in Angular 4

In PHP and HTML I just simply used to fetch data in array and show it in the select box 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 <option> tags for a <select> box from each row in the table

But how do I achieve same in Angular 4?

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

The best way would be to return the data as 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 easy.

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

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