2015-09-21 4 views
1

Мне нужно получить все мои данные из базы данных и связать их в текстовом поле с помощью angular.js и PHP. Я объясняю свой код ниже.Извлечение данных из базы данных с помощью angular.js и PHP

index.php

<?php 
include_once 'dbconfig.php'; 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>CRUD Operations With PHP and MySql - By Cleartuts</title> 
<link rel="stylesheet" href="css/style.css" type="text/css" /> 
</head> 
<body> 
<center> 

<div id="body"> 
<div id="content"> 
    <table align="center"> 
    <tr> 
    <th colspan="5"><a href="add_data.html">add data here.</a></th> 
    </tr> 
    <th>First Name</th> 
    <th>Last Name</th> 
    <th>City Name</th> 
    <th colspan="2">Operations</th> 
    </tr> 
    <?php 
$sql_query="SELECT * FROM users"; 
$result_set=mysql_query($sql_query); 
while($row=mysql_fetch_row($result_set)) 
{ 
    ?> 
     <tr> 
     <td><?php echo $row[1]; ?></td> 
     <td><?php echo $row[2]; ?></td> 
     <td><?php echo $row[3]; ?></td> 
    <td align="center"><a href="edit_data.php?edt_id=<?php echo urlencode($row[0]) ?>"><img src="images/pencil_small.png" align="EDIT" /></a></td> 
     <td align="center"><a href="javascript:delete_id('<?php echo $row[0]; ?>')"><img src="images/cross-small-icon.png" align="DELETE" /></a></td> 
     </tr> 
     <?php 
} 
?> 
    </table> 
    </div> 
</div> 

</center> 
</body> 
</html> 

Когда пользователь нажмет на кнопку редактирования он будет перенаправлять на следующую страницу (i.e-edit_data.php), которая дана ниже, и эта страница содержит все данные, которые собираются редактироваться.

edit_data.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="edit_data"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>CRUD Operations With PHP and MySql - By Cleartuts</title> 
<link rel="stylesheet" href="css/style.css" type="text/css" /> 
<script src="js/angularjs.js" type="text/javascript"></script> 
<script src="js/update.js" type="text/javascript"></script> 
</head> 

<body> 
<center ng-controller="updateController"> 
<div id="body"> 
<div id="content"> 
    <table align="center"> 
    <tr> 
    <td><input type="text" name="first_name" placeholder="First Name" ng-model="first_name" required /></td> 
    </tr> 
    <tr> 
    <td><input type="text" name="last_name" placeholder="Last Name" ng-model="last_name" required /></td> 
    </tr> 
    <tr> 
    <td><input type="text" name="city_name" placeholder="City" ng-model="city" required /></td> 
    </tr> 
    <tr> 
    <td> 
    <button type="submit" name="btn-update" ng-click="update_data();"><strong>UPDATE</strong></button> 
    </td> 
    </tr> 
    </table> 
    </div> 
</div> 

</center> 
</body> 
</html> 

На этой странице мне нужно, чтобы отобразить все неправдоподобные данные внутри текстового поля.

update.js:

var app=angular.module("edit_data", []); 
app.controller("updateController",function($scope,$http){ 
    $scope.errors = []; 
    $scope.msgs = []; 
    $scope.update_data=function(){ 
     $http.post('js/update.php',{"first_name":$scope.first_name,"last_name":$scope.last_name,"city":$scope.city} 
     ).success(function(data, status, headers, config){ 
      if(data.msg!=''){ 
      $scope.msgs.push(data.msg); 
      }else{ 
       $scope.errors.push(data.error); 
      } 
     }).error(function(data, status) { // called asynchronously if an error occurs 
       // or server returns response with an error status. 
       $scope.errors.push(status); 
     }); 
    } 
}); 

Мне нужно, чтобы получить эти три данные first_name,last_name,user_city от моего Mysql database.Please помочь мне решить эту проблему.

+0

У вас нет приложения для одной страницы. Сначала вы показываете всех пользователей на странице и для редактирования вы открываете новую страницу. Правильно ? –

+0

@brute_force: проверьте страницу index.php. – satya

ответ

0

делают PHP файл, подключения к БД и получить свой заданный параметр из БД, и после этого вызвать из углового:

var app=angular.module("myApp", []); 
app.controller("updateController",function($scope,$http){ 
$scope.errors = []; 
$scope.msgs = []; 
$scope.update_data=function(){ 
    $http.post('update.php', {"first_name":$scope.first_name,"last_name":$scope.last_name,"city":$scope.ci ty} 
    ).success(function(data, status, headers, config){ 
     $scope.resultData = data; 
    }).error(function(data, status) { // called asynchronously if an error occurs 
      // or server returns response with an error status. 
      $scope.errors.push(status); 
    }); 
} 
}); 

просмотра файла:
<div ng-controller="updateController" ng-app="myApp"> <div ng-repeat=item in resultData"> {{item.yourDbdata}} </div> </div>

ваше обновление php получить опубликованные данные вызов db и echo json_encode (результат запроса)

0
  1. Напишите функцию (скажем, retrieveData()) в php-файле для извлечения данных из базы данных.
  2. В retrieveData() после получения требуемых данных выполните echo json_encode ($ result);
  3. В вашем HTML вы можете иметь кнопку типа входного сигнала со значением = «Редактировать» и событие нг-клик = «editUser()»

  4. В контроллере Js отправить запрос на retrieveData(), т.е.

$ scope.editUser = функция() {$ HTTP ({ URL: 'path_to_function/retrieveData /', метод: 'POST', данные: "Поиск =" + $ сфера .username, заголовки: {'Content-Type': 'application/x-www-form-urlencoded'} }). Success (function (response, status, headers, config) { $ scope.result = response;
}); }

Здесь $ scope.username может быть любая вещь, например, для редактирования записи конкретного пользователя, $ scope.username будет имя пользователя этого пользователя, чтобы принести в базе данных. 5. Требуемый результат будет доступен по html в переменной $ scope.result.

Смежные вопросы