· 10 years ago · Aug 30, 2016, 07:26 AM
1using MySql.Data.MySqlClient;
2using Newtonsoft.Json;
3using System;
4using System.Collections.Generic;
5using System.Linq;
6using System.Text;
7using System.Threading.Tasks;
8
9namespace ConsoleApplication1
10{
11 public class PagesJSON
12 {
13 public string template;
14 public List<PageRowDTO> pages;
15
16 public PagesJSON()
17 {
18 template = "";
19 pages = new List<PageRowDTO>();
20 }
21 }
22 public class PageRowDTO
23 {
24 public int id;
25 public string path;
26 public string title;
27 public int views;
28
29 public PageRowDTO()
30 {
31 id = 0;
32 path = "";
33 title = "";
34 views = 0;
35 }
36 }
37 class JSONiser2
38 {
39 public void all2()
40 {
41
42 string query = "SELECT * FROM pages;";
43 string config = "server=localhost;username=root;password=;database=json";
44
45 MySqlConnection connection = new MySqlConnection(config);
46 MySqlCommand command = new MySqlCommand(query, connection);
47 connection.Open();
48 MySqlDataReader Reader = command.ExecuteReader();
49
50 PagesJSON pj = new PagesJSON();
51 pj.template = "template.html";
52
53 while (Reader.Read())
54 {
55 PageRowDTO pr = new PageRowDTO();
56 // loop on columns
57 pr.id = Int32.Parse(Reader[0].ToString());
58 pr.path = Reader[1].ToString();
59 pr.title = Reader[2].ToString();
60 pr.views = Int32.Parse(Reader[3].ToString());
61
62 pj.pages.Add(pr);
63
64 }
65
66 Console.WriteLine(JsonConvert.SerializeObject(pj));
67
68 connection.Close();
69 }
70 }
71}
72
73/**
74DROP TABLE IF EXISTS pages;
75CREATE TABLE `pages` (
76 `page_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
77 `page_path` VARCHAR(255) NOT NULL DEFAULT '',
78 `page_title` VARCHAR(255) NOT NULL DEFAULT '',
79 `page_views` INT(10) NOT NULL DEFAULT '0',
80 PRIMARY KEY (`page_id`)
81) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
82
83INSERT INTO pages (page_id, page_path, page_title, page_views) VALUES (NULL, '/', 'Root', 0);
84INSERT INTO pages (page_id, page_path, page_title, page_views) VALUES (NULL, '/index', 'Index', 0);
85INSERT INTO pages (page_id, page_path, page_title, page_views) VALUES (NULL, '/home', 'Home', 0);
86INSERT INTO pages (page_id, page_path, page_title, page_views) VALUES (NULL, '/default', 'Default', 0);
87
88SELECT * FROM pages;
89SHOW CREATE TABLE pages;
90
91
92{
93 "template": "template.html",
94 "pages": [
95 {
96 "path": "name",
97 "title": "home"
98 },
99 {
100 "path": "name",
101 "title": "home"
102 },
103 {
104 "path": "name",
105 "title": "home"
106 }
107 ]
108}
109
110<?php
111header("Content-Type: text/plain");
112
113$data = array(
114 'template' => 'template.html',
115 'pages' => array(
116 array(
117 'path' => 'name',
118 'title' => 'home',
119 ),
120 array(
121 'path' => 'name',
122 'title' => 'home',
123 ),
124 array(
125 'path' => 'name',
126 'title' => 'home',
127 ),
128 ),
129);
130
131echo json_encode($data, JSON_PRETTY_PRINT);
132
133*/