dsjk3214 2017-03-15 00:45
浏览 37
已采纳

使用PHP的Live Hosting MySQL将无法连接到我的AngularJS

After I struggling with some errors, later I've succeeded create PHP connector with my live hosting mysql, but unfortunately my AngularJS failed to connect. I create php with json format called json.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("domain","user","pass","db_name");
$result = $conn->query("SELECT UID, Name, City, Country FROM records");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"UID":"'  . $rs["UID"] . '",';
$outp .= '{"Name":"'  . $rs["Name"] . '",';
 $outp .= '"City":"'   . $rs["City"]        . '",';
$outp .= '"Country":"'. $rs["Country"]     . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>

my controller

var testAppApp = angular.module('testAppApp', []);
testAppApp.controller('SimpleController', function ($scope, $http) {
        $http.get('json.php')
        .then(function(takeprocess) {
            $scope.customers = takeprocess.data.records;
        });
});

My index.html

<html ng-app="testAppApp">
<head>
..................
..................
</head>
<div ng-controller="SimpleController">
Search <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="cust in customers | filter:filter.name">{{cust.UID}} -   
{{cust.Name}} - {{cust.City}} - {{cust.Country}}</li>
</ul>
</div>

<script src="bower_components/angular/angular.js"></script>
<script src="scripts/controllers/SimpleController.js"></script>
</body>
</html>

Actually, when I run json.php in MAMP (for testing) using Apache Server the data show like below

{"records":[{"UID":"1",{"Name":"Konohamaru","City":"Leaf Village","Country":"Konoha District"},{"UID":"2", {"Name":"Gaara","City":"Sand Village","Country":"Sand Desert Union"}]} 

This mean, I have no issue with live hosting sql server, authentication, or any. This is works well. But strangely enough when I access the php file directly with "localhost:9000/json.php" the code can't show anything, instead the browser downloading my script.

NOTE : My console not show error(s) notification too, but still when I run "Grunt Server" and take the process to open localhost:9000 my App didn't show any dummy data from my live host DB. But when I testing with data.json, for the purpose if my code actually works, voila the good thing happen, my data showing. I still confuse, where I was wrong in this process, please help. Thanks in advance

  • 写回答

1条回答 默认 最新

  • douchuifk90315 2017-03-15 11:54
    关注

    Okay, I made it self finally. First, I don't know it proxy issue or what. But since I know grunt can't execute PHP file (before modified), later I search where the wrong my project.

    First, I've indicated Grunt Server can't execute PHP, so I must modify gruntfile.js based on this article "Use PHP with your Yeoman dev server" but honestly, there is no softly step by step how and where you can put your code. In shortcut, here I put my code in Gruntfile.js (near top)

    // Generated on 2017-03-13 using generator-angular 0.16.0
    'use strict';
    var lrSnippet = require('grunt-contrib-       
    livereload/lib/utils').livereloadSnippet;
    var gateway = require('gateway');
    var mountFolder = function (connect, dir) {
    return connect.static(require('path').resolve(dir));
    }; 
    

    And here....

     livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              lrSnippet,
              gateway(__dirname + '/app', {
              '.php': 'php-cgi'}),
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'app'),
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect().use(
                '/app/styles',
                connect.static('./app/styles')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
    

    In specific section, I add below return [ .....

    lrSnippet,
              gateway(__dirname + '/app', {
              '.php': 'php-cgi'}),
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'app'),
    

    After that, I edit my json.php like below

    <?php
    //open connection to mysql db
    $connection = mysqli_connect("hosting","username","pass","db_name") or die("Error " . mysqli_error($connection));
    
    //fetch table rows from mysql db
    $sql = "select * from records";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
    
    //create an array
    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    
    header('Content-Type: application/json');
    echo json_encode($emparray);
    
    //write to json file
    //$fp = fopen('data.json', 'w');
    //fwrite($fp, json_encode($emparray));
    //fclose($fp);
    
    //close the db connection
    mysqli_close($connection);
    ?>
    

    And edit my controller little bit

    var testAppApp = angular.module('testAppApp', []);
    testAppApp.controller('SimpleController', function ($scope, $http) {
            $http.get('json.php')
            .then(function(takeprocess) {
                $scope.customers = takeprocess.data;
            });
    });
    

    Later, I start "Grunt Build" and try "Grunt Server". My App show in localhost:9000 but still blank, but when I change my Wifi. My App works like charm, I can connecting my Live hosting MySQL with my local Grunt.

    But, it seems I have complicated thing, My Grunt not supporting to read PHP before, and I suspect my network not stable or have proxy issue, I don't know. But when I try again, clean my project with default setting (without gateway setting in Gruntfile.js). My app have error(s) again.

    I hope this help to everyone who have same experience with me.

    NOTE : There are several dependencies you must done, Install gateway in your project not global

    npm install gateway
    

    If you notice here...

    var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
    

    variable LrSnippet need dependencies grunt-contrib-
    livereload, just do

    npm install grunt-contrib-livereload
    

    sudo if needed

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败