dustsensor.ino

dustsensorv2.ino



첨부된 2 가지  케이스로 코딩됨.

미세먼지 측정센서로 측정된 미세먼지 농도를 
16x2 LCD 에 표현하기.


아두이노 코딩도 계속하다 보니 자연스럽게 되는것 같다. 전자회로도 또한 친숙해지는것 같고.
연습이 완벽하게 만든다고 했나? 생각보다 쉽게 만들어짐에 놀라웠다.

Practice makes perfect, thanks.


#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int Vo = A0;
int V_LED = 2;

float Vo_value = 0;
float Voltage = 0;
float dustDensity = 0;
float dustCleanVoltage = 0.44;
int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

void setup(){
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("dust");
Serial.begin(9600);

/*digital output:*/
pinMode(V_LED, OUTPUT);

/*analog input:*/
pinMode(Vo, INPUT);
}

/** references :
* http://blog.naver.com/PostView.nhn?blogId=darknisia&logNo=221222455928
* http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/
* */
// 미세먼지 센서(GP2Y1010AU0F)
// : 적외선 발광 다이오드(IRED)와 포토다이오드가 대각선으로 배치되어 공기 중 먼지의 반사광을 감지
void loop(){
digitalWrite(V_LED,LOW); //ired 'on'
delayMicroseconds(samplingTime);
Vo_value = analogRead(Vo); //read the dust value
delayMicroseconds(deltaTime);// pulse width 0.32 - 0.28 = 0.04 msec
//0.32 msec의 펄스폭을 유지하기 위해 필요한 코드입니다

digitalWrite(V_LED,HIGH); //ired 'off'
delayMicroseconds(sleepTime);


/*
이 센서의 출력전압(Vo)는 먼지가 없을 때의 출력전압(Voc)과 먼지 농도(ΔV)에 비례하여 출력됩니다.
다시 표현하면 ΔV = Vo – Voc
미세먼지 농도[µg/m³] = (Vo – Voc) / 0.005
*/
Voltage = Vo_value * (5.0 / 1024.0);

dustDensity = (Voltage - dustCleanVoltage)/0.005;

Serial.print(" Raw Signal Value (0-1023):");
Serial.print(Vo_value);
Serial.print(" | Volatage:");
Serial.print(Voltage);
Serial.print(" | Dust Density:");
Serial.print(dustDensity);
Serial.print("[ug/m3]");
if(dustDensity<31){
Serial.println(" => [Great(~30)]");
} else if(dustDensity>30 && dustDensity<81){
Serial.println(" => [Good(31~80)]");
} else if(dustDensity>81 && dustDensity<151){
Serial.println(" => [Bad(81~150)]");
} else{
Serial.println(" => [Too Bad(151~)]");
}


// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 0);
lcd.print(dustDensity);
lcd.setCursor(0, 1);
if(dustDensity<31){
lcd.print(": Great(~30)");
} else if(dustDensity>30 && dustDensity<81){
lcd.print(": Good(31~80)");
} else if(dustDensity>81 && dustDensity<151){
lcd.print(": Bad(81~150)");
} else{
lcd.print(": Too Bad(151~)");
}
delay(5000);
}


 

자바스크립트로 fb API연동하여 로그인하기



그래프 API 탐색기 이용하기

url : https://developers.facebook.com/tools-and-support 



appid 에서 가져올 권한 선택추가 선택


default : id, name 

추가로 가져올 정보 : email






위 api 탐색기로 선 테스트 후 

아래처럼 javascript로 코드작성.

참고url : https://developers.facebook.com/docs/facebook-login/web#logindialog



<<html code>>


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--
reference to : https://developers.facebook.com/tools-and-support
-->
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '2028791704043595',
     cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v3.0' // use graph api version 2.8
});
    FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};

(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

   /*
     콜백에 제공되는 response 개체에는 다음과 같은 여러 필드가 포함되어 있습니다.
    {
        status: 'connected',
        authResponse: {
            accessToken: '...',
            expiresIn:'...',
            signedRequest:'...',
            userID:'...'
        }
    }코드 복사
    status는 앱 사용자의 로그인 상태를 지정합니다. 상태는 다음 중 하나일 수 있습니다.
    connected - 사용자가 Facebook에 로그인하고 앱에 로그인했습니다.
    not_authorized - 사용자가 Facebook에는 로그인했지만 앱에는 로그인하지 않았습니다.
    unknown - 사용자가 Facebook에 로그인하지 않았으므로 사용자가 앱에 로그인했거나 FB.logout()이 호출되었는지 알 수 없어,
Facebook에 연결할 수 없습니다.
    connected 상태인 경우 authResponse가 포함되며 다음과 같이 구성되어 있습니다.
    accessToken - 앱 사용자의 액세스 토큰이 포함되어 있습니다.
    expiresIn - 토큰이 만료되어 갱신해야 하는 UNIX 시간을 표시합니다.
    signedRequest - 앱 사용자에 대한 정보를 포함하는 서명된 매개변수입니다.
    userID - 앱 사용자의 ID입니다.
    앱에서 앱 사용자의 로그인 상태를 알게 되면 다음 중 하나를 수행할 수 있습니다.
    사용자가 Facebook과 앱에 로그인한 경우 앱의 로그인된 환경으로 리디렉션됩니다.
    사용자가 앱에 로그인하지 않았거나 Facebook에 로그인하지 않은 경우 FB.login()을 사용하여 로그인 대화 상자에 메시지를
표시하거나 로그인 버튼을 표시합니다.
        */
   function statusChangeCallback(response) {
    
      console.log('statusChangeCallback');

      if (response.status === 'connected') {
        console.log(response.authResponse.accessToken);
        // Logged into your app and Facebook.
        testAPI();
      } else if (response.status === 'not_authorized') {
        document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
      } else {
        document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';
      }

  }

function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
  
function testAPI() {
  console.log('Welcome! Fetching your information.... ');
  FB.api(
    '/me',
    {"fields":"id,name,email"},
    function(response) {
       // Insert your code here
      console.log('Successful login for: ' + response.name);

      document.getElementById('status').innerHTML = JSON.stringify(response);
    }
  );
}

function fblogout(){

  FB.logout(function(response) {
    window.location.reload();
  });
}

</script>

<fb:login-button
scope="public_profile,email"
onlogin="checkLoginState();">
</fb:login-button>

<input type="button" onclick="javascript:fblogout();" value ="로그아웃" />
<div id="status"/>

</body>
</html>


로그인페이지>>


로그인후 fb의 개인정보 받아 display



로그인은 잘 되나, 로그아웃은 아래와 같은 에러내용으로 console log를 찍고 로그아웃이 안되고 있음. 

유투브 동영상등 찾아보고 진행했지만 해결못함.


Refused to display 'https://www.facebook.com/home.php' in a frame because it set 'X-Frame-Options' to 'deny'.


'프로그래밍 > PHP' 카테고리의 다른 글

curl kakao open api사용하기  (0) 2018.08.05
php CURL 사용하기  (0) 2018.07.31
php 패스워드 암호화 bcript  (0) 2018.05.02
unlink(=delete) 메소드 이용하기  (0) 2018.04.22
directory entry 읽어 파일리스트업  (0) 2018.04.20

스크린스크래핑

WebBrowser이용해서 website에 렌더링된 html의 특정값을 추출한다.

예를 들어 특정 사이트 모 카테고리에 있는 내용을 모두 가져와서 데이터화하고 그것을 분석하고 싶을 때 스크래핑을 사용하면 편리하다.

 

아래 code

 

특정 카테고리의의 글list를 통해 key, title을 추출하고

Key를 이용해 본문내용의 text를 가져와서 db화 한 내용이다.

글의 pattern등 분석자료로 사용할 목적으로 데이터가 필요하나 해당사이트에서 DB를공개하진 않으니 이렇게 스크랩핑해서 자료화해서 사용하는 것이다.

이렇게 하지 않으면 사이트의 모든 사이트 내용을 클릭~클릭~클릭~ 하겠지.

 

이렇게 프로그램하기 전에 사전에 해당 사이트를 분석하고 맞게 프로그래밍하면 된다.


step1) 카테고리의의 글list를 통해 key, title을 추출 : webSiteContentsList();

 => 추출된 data를 수작업으로 insert스크립트만들어 TMP_HELP 에 insert함.

step2) Key를 이용해 본문내용의 text를 가져와서 db화 한 내용 : webSiteContentsDetail(oBrowser);


<c# code>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient;

namespace ScrappingWinForms
{
public partial class Form1 : Form
{

int iq = 0;
string contentsKey = "";

string sConnectionString = "Server=localhost;contentsKey=root;Pwd=???;Database=??????";
string sContentsUrl = "http://www.doitforyou.co.kr/sread.html?key="; //fake url임
string sListUrl = "http://www.doitforyou.co.kr/sub.html?&sec=cc&section=culture&page="; //fake url임

String Url = string.Empty;

public Form1()
{
InitializeComponent();

//WebBrowser로 사이트 로딩시 자바스크립트 바인딩안되어 에러나는 경우.
//자바스크립트 오류(dialogbox) 무시하고 진행가능하도록 제어함.
this.webBrowserViewer.ScriptErrorsSuppressed = true;
webBrowserViewer.DocumentTitleChanged += new EventHandler(webBrowserViewer_DocumentTitleChanged);
}
private void btnSearch_Click(object sender, EventArgs e)
{
// surftheWeb();
if (iq < 200)
{
selectContentsKeyfromWebsite();
}
}

#region surftheWeb :WebBrowser에 SitePage 브라우징한다.
private void surftheWeb()
{
Url = txtUrl.Text;
webBrowserViewer.Navigate(Url);
}

private void surftheWeb(String sUrl)
{
webBrowserViewer.Navigate(sUrl);
}

#endregion


#region Select / Update from the WebSite

private void selectContentsKeyfromWebsite()
{
MySqlConnection oConnection = new MySqlConnection(sConnectionString);
oConnection.Open();

try
{
MySqlCommand cmd = oConnection.CreateCommand();
cmd.CommandText = "SELECT HELP_TOPIC_ID FROM TMP_HELP WHERE HELP_TOPIC_ID >= 100 AND DESCRIPTION = '' LIMIT 1";
MySqlDataAdapter aDap = new MySqlDataAdapter(cmd);
DataSet dsData = new DataSet();
aDap.Fill(dsData);
if (contentsKey != dsData.Tables[0].Rows[0][0].ToString())
{
contentsKey = dsData.Tables[0].Rows[0][0].ToString();
String sUrl = String.Empty;
sUrl = sContentsUrl + contentsKey;
surftheWeb(sUrl);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oConnection.State == ConnectionState.Open)
{
oConnection.Close();
}
}
}
/// <summary>
/// key값으로 contents내용을 업데이트 한다.
/// </summary>
/// <param name="sHelp_topic_id"></param>
/// <param name="sDescription"></param>
private void updateContentonIldaro(String sHelp_topic_id, String sDescription)
{
MySqlConnection oConnection = new MySqlConnection(sConnectionString);
oConnection.Open();

try
{
MySqlCommand cmd = oConnection.CreateCommand();
cmd.CommandText = "UPDATE tmp_help set description = @description where help_topic_id = @help_topic_id";
cmd.Parameters.AddWithValue("@help_topic_id", int.Parse(sHelp_topic_id));
cmd.Parameters.AddWithValue("@description", sDescription);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oConnection.State == ConnectionState.Open)
{
oConnection.Close();

//key를 다시 조회한다.
btnSearch_Click(null, null);
}
}
}
#endregion

/// <summary>
/// WebBrowser's DocumentCompleted Event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webBrowserViewer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser oBrowser = sender as WebBrowser;
//txtSource.Text = StreamConvertEUCKRtoUTF8(oBrowser);

this.txtUrl.Text = oBrowser.Url.AbsoluteUri;

//webSiteContentsList();
webSiteContentsDetail(oBrowser);
}

private void webSiteContentsDetail(WebBrowser oBrowser)
{
iq++; //반복수행위한 카운팅
getWebSiteContentsDetail(oBrowser);
}

/// <summary>
/// 게시판 글list, Paging있음
/// </summary>
private void webSiteContentsList() {

iq++; //paging 숫자

getData();

if (iq < 21)
{
String sUrl = sListUrl + iq.ToString();
surftheWeb(sUrl);
}
}

/// <summary>
/// 1.WebBrowser로 rendering된 html을 TagName으로 HtmlElementCollection에 담는다.
/// 2.HtmlElementCollection => HtmlElement에 담긴 InnerHtml분석한다.
/// 3.HtmlElement[]에 추출하려는 대상을 담는다.
/// </summary>
/// <param name="wb"></param>
/// <param name="tagName"></param>
/// <returns></returns>
private HtmlElement[] GetElementsByTagName(WebBrowser wb, string tagName)
{
var l = new List<HtmlElement>();

var els = wb.Document.GetElementsByTagName(tagName); // all elems with tag
foreach (HtmlElement el in els)
{
if (el.InnerHtml == null)
{
continue;
}

if(el.InnerHtml.StartsWith("<A href=\"read.html"))
{
l.Add(el);
}
}

return l.ToArray();
}


/// <summary>
/// 1.WebBrowser로 rendering된 html을 TagName으로 HtmlElementCollection에 담는다.
/// 2.HtmlElementCollection => HtmlElement에 담긴 요소들중 className을 이용해서 추출하려는 대상을 뽑는다..
/// 3.HtmlElement[]에 추출하려는 대상을 담는다.
/// </summary>
/// <param name="wb"></param>
/// <param name="tagName"></param>
/// <param name="className"></param>
/// <returns></returns>
private HtmlElement[] GetElementsByTagNClassName(WebBrowser wb, string tagName, string className)
{
var l = new List<HtmlElement>();

var els = wb.Document.GetElementsByTagName(tagName); // all elems with tag
foreach (HtmlElement el in els)
{

if (el.GetAttribute("className") == className)
{
l.Add(el);
}
}

return l.ToArray();
}

/// <summary>
/// 글 상세 페이지에서 추출하고자 하는 Text만 가져온다.
/// </summary>
/// <param name="oBrowser"></param>
private void getWebSiteContentsDetail(WebBrowser oBrowser)
{
var arrCollection = GetElementsByTagNClassName(webBrowserViewer, "td", "contentsbody");
for (int i = 0; i < arrCollection.Length; i++)
{
//Console.WriteLine(arrCollection[i].InnerHtml);

String sText = String.Empty;
//sText = arrCollection[i].InnerHtml;
sText = arrCollection[i].OuterText;

if (sText == null)
{
//글 text가 없는 경우가 있음
//case1) 이미지로 대체한 경우 img html tag가 글 대신 있음
sText = arrCollection[i].InnerHtml;
}
if (contentsKey.Equals(oBrowser.Url.AbsoluteUri.Replace(sContentsUrl, "")))
{
updateContentonIldaro(contentsKey, sText);
}
}
}

private void getData() {

// getting day and night temperature
var arrCollection = GetElementsByTagName(webBrowserViewer, "dt");

DataTable dt = new DataTable();

dt.Columns.Add("contentsKey", typeof(int));
dt.Columns.Add("Title", typeof(string));

Console.WriteLine("-- " + iq.ToString() + " --------------");
txtSource.Text = txtSource.Text + "-- " + iq.ToString() + " --------------" + "\r\n";

for (int i = 0; i < arrCollection.Length; i++) {
//Console.WriteLine(arrCollection[i].InnerHtml);

String sText = String.Empty;
sText = arrCollection[i].InnerHtml;
sText = sText.Replace("<A href=\"sread.html?key=", "").Replace("</A>", "").Replace("\"", "");

String[] arrSplit = sText.Split('>');

dt.Rows.Add(arrSplit[0],arrSplit[1]);

Console.WriteLine(arrSplit[0] + ":" + arrSplit[1]);

txtSource.Text = txtSource.Text + arrSplit[0] + ":" + arrSplit[1] + "\r\n";

}

}

#endregion


reference to :  https://www.codeproject.com/Tips/858775/Csharp-Website-HTML-Content-Parsing-or-How-To-Get


'프로그래밍 > c#' 카테고리의 다른 글

c#에서 mariadb사용하기  (0) 2018.11.10
WebBrowser.DocumentText 한글깨짐  (0) 2018.05.07
using MySqlConnector  (0) 2018.05.07

WebBrowser 객체를 이용해서 web페이지를 볼 때 DocumentText 메소드로 렌더링된 html을 읽어올 때 default utf-8 encoding type이라 이상태에서는 euc-kr의 한글은 깨진다

이 경우 스트림리더를 사용해서 실제 페이지의 encoding type으로 읽어들이면 된다.

 

샘플) WebBrowser.DocumentText 로 소스를 봤을경우.

 

<html>

<head>

<title><��̴ϽƮ ���� �ϴ�></title>

<meta http-equiv="Content-Type" content="text/html; charset=euc-kr" />

 

 

StreamReader를 이용해 페이지의 encoding type으로 읽어들인경우

 

<html>

<head>

<title><오늘은 어린이날 입니다></title>

 

<<C# Code>>

 

/// <summary>

        /// WebBrowser's DocumentCompleted Event

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void webBrowserViewer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

        {

            // ((WebBrowser)sender).Document.Window.Error +=   new HtmlElementErrorEventHandler(Window_Error);

 

            WebBrowser oBrowser = sender as WebBrowser;

 

            txtSource.Text = StreamConvertEUCKRtoUTF8(oBrowser);

                       

        }

 

        /// <summary>

        /// Using WebBrowser web page

        /// 웹페이지 Encoding type EUC-KR 이면 WebBrowser.DocumentText html 렌더링된 text 볼때 한글이 깨진다.

        /// 아래처럼 스트림리더로 EUC-KR type으로 읽어온다.

        /// </summary>

        /// <param name="oBrowser"></param>

        /// <returns></returns>

        private String StreamConvertEUCKRtoUTF8(WebBrowser oBrowser)

        {

            String sResult = String.Empty;

 

            Stream oStream;

            StreamReader oStreamReader;

            oStream = oBrowser.DocumentStream;

            oStreamReader = new StreamReader(oStream, System.Text.Encoding.GetEncoding(oBrowser.Document.Encoding));

            oStream.Position = 0;

            sResult = oStreamReader.ReadToEnd();

 

            return sResult;

        }


'프로그래밍 > c#' 카테고리의 다른 글

c#에서 mariadb사용하기  (0) 2018.11.10
WebBrowser이용한 스크린스크래핑  (0) 2018.05.09
using MySqlConnector  (0) 2018.05.07


c#에서 Mariadb를 연결할때 MySqlConnector를 사용한다.

VS에서 NgGet을 이용해서 쉽게 검색하고 설치할 수 있다. 

*NgGet 이놈 참 좋다~


MySqlConnector는 MIT 라이센스 그냥 사용하면 된다.





connector설치한김에 테스트까지 해봐야지요



c#코드


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.IO;

using MySql.Data.MySqlClient;


namespace ScrappingWinForms

{

    public partial class Form1 : Form

    {

        string sConnectionString = "Server=localhost;Uid=root;Pwd=???????;Database=???";


        String Url = string.Empty;


        public Form1()

        {

            InitializeComponent();


            //WebBrowser로 사이트 로딩시 자바스크립트 바인딩안되어 에러나는 경우.

            //자바스크립트 오류(dialogbox) 무시하고 진행가능하도록 제어함. 

            this.webBrowserViewer.ScriptErrorsSuppressed = true;

            webBrowserViewer.DocumentTitleChanged += new EventHandler(webBrowserViewer_DocumentTitleChanged);

        }


        private void btnSearch_Click(object sender, EventArgs e)

        {

            surftheWeb();

        }

        

        private void surftheWeb()

        {

            Url = txtUrl.Text;

            webBrowserViewer.Navigate(Url);

        }


        /// <summary>

        /// WebBrowser's DocumentCompleted Event

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void webBrowserViewer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

        {

            // ((WebBrowser)sender).Document.Window.Error +=   new HtmlElementErrorEventHandler(Window_Error);


            WebBrowser oBrowser = sender as WebBrowser;


            txtSource.Text = StreamConvertEUCKRtoUTF8(oBrowser);

                        

        }


        /// <summary>

        /// Using WebBrowser web page 

        /// 웹페이지 Encoding type 이 EUC-KR 이면 WebBrowser.DocumentText로 html로 렌더링된 text를 볼때 한글이 깨진다.

        /// 아래처럼 스트림리더로 페이지 EUC-KR type을 읽어들인다.

        /// </summary>

        /// <param name="oBrowser"></param>

        /// <returns></returns>

        private String StreamConvertEUCKRtoUTF8(WebBrowser oBrowser)

        {

            String sResult = String.Empty;


            Stream oStream;

            StreamReader oStreamReader;

            oStream = oBrowser.DocumentStream;

            oStreamReader = new StreamReader(oStream, System.Text.Encoding.GetEncoding(oBrowser.Document.Encoding));

            oStream.Position = 0;

            sResult = oStreamReader.ReadToEnd();


            return sResult;

        }

         

        private void webBrowserViewer_DocumentTitleChanged(object sender, EventArgs e)

        {

            //this.Text = webBrowser1.DocumentTitle.ToString();


            this.groupBox1.Text = webBrowserViewer.DocumentTitle;

        }



        private void loadTestData() {

            MySqlConnection oConnection = new MySqlConnection(sConnectionString);

            oConnection.Open();


            try

            {

                MySqlCommand cmd = oConnection.CreateCommand();

                cmd.CommandText = "SELECT * FROM TMP_help order by help_topic_id desc";

                MySqlDataAdapter aDap = new MySqlDataAdapter(cmd);

                DataSet dsData = new DataSet();

                aDap.Fill(dsData);


                dgViewSample.DataSource = dsData.Tables[0].DefaultView;


            }

            catch (Exception ex)

            {

                throw ex;

            }

            finally {

                if (oConnection.State == ConnectionState.Open)

                {

                    oConnection.Close();

                }

            }

        }

      


        private void btnForTest_Click(object sender, EventArgs e)

        {

            loadTestData();

        }

     

    }

}



'프로그래밍 > c#' 카테고리의 다른 글

c#에서 mariadb사용하기  (0) 2018.11.10
WebBrowser이용한 스크린스크래핑  (0) 2018.05.09
WebBrowser.DocumentText 한글깨짐  (0) 2018.05.07

DB를 핸들링하는 server-side 언어, php

반응형웹페이지디자인 : bootstrap

자바스크립트기반 웹어플리케이션 프레임웍 : angularjs

이것 3개 조합해서 웹페이지 만들기.


xmlhttp, ajax, jquery등 다양한 스크립트 형식의 모듈들이 많이 있었지만.

angularjs는 MVC패턴의 자바스크립트 프로그램방식으로 진행된다.

자바스크립트로 진행되지만 스크립트 같지 않은 아주 다양한 기능과 표준화, 개인생각임.. ㅋㅋ

모바일 웹앱만들때 가장 좋은것 같다.


angularjs를 적용한 html 페이지소스.




<html lang="en" ng-app="myApp">
<head>
...
 

        
Full Name: {{firstName + " " + lastName}}

Calc using AngularJs, expression: {{ 5 + 5 }}

{{ y.help_topic_id }} : {{ y.name }}
… /*angularjs 스크립트 적용부분은 웹페이지 맨 하단에 적용*/




angularjs 문법이 궁금하면, https://www.w3schools.com/angular/default.asp

'프로그래밍 > PHP' 카테고리의 다른 글

파일 업로드(move_uploaded_file)  (3) 2018.04.14
fileupload 에러메시지 설명  (0) 2018.04.14
json 데이타 사용하기  (0) 2018.03.28
Cookie 사용하기  (0) 2018.03.18
Session 사용하기  (0) 2018.03.17


json 데이타 사용하기

refer to : https://www.w3schools.com/js/js_json_php.asp


JSON type 을 이용해서 data 송수신하려 함.
PHP에서 제공하는 함수 json_encode/json_decode 사용
 


아래는 Database를 이용한 예제로 fetch후 data를 json_encode() 하여 화면에 뿌린것이다.



vJsonData1.php
getSomeTopics();

echo "{\"Table\":". json_encode($topics)."}";
?>
TopicData.php
    public function getSomeTopics()
    {
        $query = $this->connection->prepare("SELECT help_topic_id, name FROM TMP_help order by help_topic_id desc  limit 10 ");
        $query->execute();

        //return $query;

        return $query->fetchAll(\PDO::FETCH_ASSOC);
        
    }





'프로그래밍 > PHP' 카테고리의 다른 글

fileupload 에러메시지 설명  (0) 2018.04.14
angularJS 사용하기  (0) 2018.04.01
Cookie 사용하기  (0) 2018.03.18
Session 사용하기  (0) 2018.03.17
반응형 웹개발 admin 페이지 step1  (0) 2018.03.04

Session과 Cookies는 같이 적절히 사용하면 사이트 운영에 효율적임.



>>refer to : https://www.w3schools.com/php/php_cookies.asp 

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.


domain 파라미터를 이용하면 해당 도메인에서만 쿠키가 적용됨.


sessionstep21.php에 cookie적용하고 sessionstep2.php open시 cookie를 화면으로 확인
sessionstep21.php 코드보기


";
var_dump($_POST);
?>

 0) {

    $snEmail =  $_POST['exampleInputEmail1'];
    $snId = "doitforyou";
    $snGroup = "MASTER";
    $snSdate = date("YmdHis");

    echo "

"; echo "세션 ID : ".session_id(); echo "
"; echo "
저장할 이메일 : ".$snEmail; echo "
저장할 ID : ".$snId; echo "
저장할 그룹 : ".$snGroup; // 세션에 저장 $_SESSION['snEmail'] = $snEmail; $_SESSION['snId'] = $snId; $_SESSION['snGroup'] = $snGroup; $_SESSION['snSdate'] = $snSdate; echo "
세션생성완료"; $cookie_name = "cnEmail"; $cookie_value = $snEmail; setcookie($cookie_name, $cookie_value, time() + (86400 * 1), "/", "doitforyou.co.kr"); // 86400 = 1 day } ?> go to the next, sessionStep2 => CLICK


doitforyou.co.kr 도메인에서 cookie 적용됨


타도메인에서는 cookie 적용안됨


'프로그래밍 > PHP' 카테고리의 다른 글

angularJS 사용하기  (0) 2018.04.01
json 데이타 사용하기  (0) 2018.03.28
Session 사용하기  (0) 2018.03.17
반응형 웹개발 admin 페이지 step1  (0) 2018.03.04
PHP Programming 해보기  (0) 2018.03.02

 

1.    APM 설치

아파치 : httpd-2.4.27-Win64-VC15.zip

DB : mariadb-10.0.33-winx64.msi

언어 : php-7.1.7-Win32-VC14-x64.zip

DB연결 Tools : ToadforMySQL_Freeware_8.0.0.296

 

 

2.    APM setting
: apache, php
의 설정파일을 수정.

 

2.1. httpd.conf

설치된 로컬 경로로 수정.

C:\APMorg\Apache24\conf\httpd.conf 파일 편집

#######################################################

#

ServerRoot "c:/APMorg/Apache24"

 

#

DocumentRoot "c:/APMorg/Apache24/htdocs"

<Directory "c:/APMorg/Apache24/htdocs">

 

#

ScriptAlias /cgi-bin/ "c:/APMorg/Apache24/cgi-bin/"

 

<Directory "c:/APMorg/Apache24/cgi-bin">

    AllowOverride None

    Options None

    Require all granted

</Directory>

 

#--php.ini 파일을 c:\windows 폴더에 복사해 넣음(php.ini파일 편집 에서 재 확인)

 

PHPIniDir "C:/Windows"

LoadModule php7_module "C:/APMorg/php/php7apache2_4.dll"

 

#######################################################

 

2.2. php.ini

C:\APMorg\php\php.ini-development 파일 편집하여 라이브러리 사용 가능하도록 수정

 

; Directory in which the loadable extensions (modules) reside.

; http://php.net/extension-dir

extension_dir = "C:\APMorg\php\ext\"

 

;extension=php_exif.dll      ; Must be after mbstring as it depends on it

extension=php_mysqli.dll

;extension=php_pdo_firebird.dll

extension=php_pdo_mysql.dll

;extension=php_pdo_oci.dll

 

=> C:\Windows\php.ini 로 저장  

 

3.    Apache, PHP 구동확인

 

웹서버 경로 ( C:\APMorg\Apache24\htdocs ) 에서

phpinfo.php파일을 만들고

아래 script를 쳐주면

 

<?php

phpinfo();

?>

 

php가 연결된 여러 정보들이 list-up된다. 해당 정보를 잘 활용하면 환경세팅에 도움이 된다.   

   



 

4.    테스트 데이타

: Mariadb install => Database : mysql => Table : HELP_TOPIC

 

임시테이블로 생성후 진행

create table TMP_HELP as
select * from help_topic;

 

TMP_HELP 테이블 데이터로 CRUD 테스트 진행한다.

 

alter table TMP_HELP2 add PRIMARY KEY (`help_topic_id`); pk까지 생성한다.

 

 

5    프로그래밍 패턴

                   http://phpbridge.org/intro-to-php/ 를 기준으로 진행함.

            구글링 해서 찾은 강의 중에 가장 좋음.

          

            만든 결과물 : http://doitforyou.co.kr/test/public/

            


            

           

              



'프로그래밍 > PHP' 카테고리의 다른 글

angularJS 사용하기  (0) 2018.04.01
json 데이타 사용하기  (0) 2018.03.28
Cookie 사용하기  (0) 2018.03.18
Session 사용하기  (0) 2018.03.17
반응형 웹개발 admin 페이지 step1  (0) 2018.03.04

+ Recent posts