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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题