繁体   English   中英

使用LAMP服务器上的PHP从MySQLi输出JSON API

[英]JSON api output from MySQLi using PHP on LAMP server

我正在构建一个在RDS实例上具有MySQL数据库的应用程序,我希望能够通过api将数据提供给网络/移动应用程序。 因此,我为Web服务构建了一个Ubuntu Lamp服务器EC2实例。

在/ var / www / html /中,我创建了第一个php脚本;

<?php
class ArticlesAPI {
    private $db;

    function __construct() {
        $this->db = new mysqli("mysql-host.rds.amazonaws.com", "user", "password", "dbname");
        $this->db->autocommit(FALSE);
    }

    function __destruct() {
        $this->db->close();
    }

    function top() {
        $stmt = $this->db->prepare("SELECT article_id, title, summary, article, image FROM top_articles;");
        $stmt->execute();
        $stmt->bind_result($article_id, $title, $summary, $article, $image);

        while ($stmt->fetch()) {
            echo "$article_id";
            echo "$title";
            echo "$summary";
            echo "$article";
            echo "$image";
        }
        $stmt->close();
    }
}

$api = new ArticlesAPI;
$api->top();

?>

这将产生所需的输出,但是它只是一小段文本。 所以我想添加一个json_encode()。 我已经按如下方式更改了功能;

    function top() {
            $stmt = $this->db->prepare("SELECT article_id, title, summary, article, image FROM top_articles;");
            $stmt->execute();
            $stmt->bind_result($article_id, $title, $summary, $article, $image);

            $this->rows = array();

            while ($stmt->fetch()) {
                    $rows['article_id'] = $article_id;
                    $rows['title'] = $title;
                    $rows['summary'] = $summary;
                    $rows['article'] = $article;
                    $rows['image'] = $image;
            }
            $stmt->close();
            echo json_encode($rows);
    }

它返回终端查询中的最后一条记录,当我尝试通过浏览器使用它时,它似乎在查询数据库,但它不返回任何内容。 我是JSON,PHP和API的新手。 任何帮助,将不胜感激。

这是创建所需输出的简单得多的方法。

<?php
class ArticleAPI {

        function top() {
                $db = new  mysqli("mysql-host.rds.amazonaws.com", "user", "password", "dbanme");
                $results = $db->query("SELECT article_id, title, summary FROM top_articles");

                $articles = array();
                while($article = $results->fetch_assoc()){
                        $article_id = $article['article_id'];
                        $articles[$article_id][] = $article['title'];
                        $articles[$article_id][] = $article['summary'];
                }
                $results->close();
                $db->close();
                $json = json_encode($articles);
                echo $json;

        }
}
$api = new ArticleAPI;
$api->top();
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM