FCM 을 활용한 PUSH 메세지 보내기 (2022-10-19)

프로그래밍/ANDROID|2022. 10. 19. 16:16
반응형

New Project > Empty Activity 선택

Language : Java

Minimum SDK : API 21

[v] Use legacy android.support libraries

이 상태로 진행하였습니다.

 

 

build.gradle 수정 (프로젝트 수준)

 

아래 내용을 파일 내용 맨 윗부분에 추가 합니다.

 

buildscript {
    repositories {
        google()  // Google's Maven repository
        mavenCentral()  // Maven Central repository

    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.14'
    }
}

(생략)

 

 

build.gradle 수정 (앱 수준)

 

아래 내용을 추가 합니다.

중간에 주석 부분도 추가해줍니다. 없을 경우 바로 아랫줄에 구문 에러 메세지가 출력됩니다.

 

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services' // 이 부분을 추가 합니다.
}

(생략)

dependencies {

    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:2.0.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation platform('com.google.firebase:firebase-bom:31.0.0')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-messaging:23.1.0'
    implementation 'com.google.firebase:firebase-core:21.1.1'
}

apply plugin: 'com.google.gms.google-services'

 

 

settings.gradle 생성 (앱 수준)

 

allprojects {
    repositories {
        google()  // Google's Maven repository
        mavenCentral()  // Maven Central repository
    }
}

 

 

google-services.json 생성

 

Firebase console 페이지에 접근해서 프로젝트에 APP 을 추가합니다.

추가하는 과정에서 google-services.json 파일을 다운로드 받을 수 있으며,

해당 파일은 app 디렉토리 안에 넣어 놓습니다.

 

 

build.gradle 페이지에서 [Sync Now] 버튼을 눌러줍니다.

 

 

MyFirebaseMessagingService.java 생성

 

package com.tistory.sysdocu;

import androidx.annotation.NonNull;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        //token을 서버로 전송
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        //수신한 메시지를 처리
    }
}

 

 

MainActivity.java 수정

 

package com.tistory.sysdocu;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.messaging.FirebaseMessaging;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FirebaseMessaging.getInstance().getToken().addOnSuccessListener(new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String token) {

                // 토큰을 토스트로 간단히 확인
                Toast toast = Toast.makeText(getApplicationContext(), "TOKEN : " + token, Toast.LENGTH_LONG);
                toast.show();

// 아래와 같이 특정 서버로 데이터를 전송 할 수 있습니다. 
// 서버로 token 을 전송하는 방식은 여러가지가 있으나, 여기에서는 간단히 GET 방식으로 접근하여 전송하도록 하였습니다.
// 웹서버에서는 token 을 DB 에 저장하여 활용하면 됩니다.
/*
                new Thread(){
                    @Override
                    public void run() {
                        StringBuilder content = new StringBuilder();
                        try {
                            URL url = new URL("https://sysdocu.tistory.com/register.html?token=" + token);
                            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                            String str;
                            while ((str = in.readLine()) != null) {
                                content.append(str +"\n");
                            }
                            in.close();
                        } catch (MalformedURLException e) {
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
*/
            }
        });
    }

}

 

 

activity_main.xml 수정

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="#DFE5E5"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/black"
        android:text="토큰은 웹서버에서 확인하세요." />

</LinearLayout>

 

 

AndroidManifest.xml

 

아래 내용을 추가합니다.

 

(생략)

<uses-permission android:name="android.permission.INTERNET"/>


(생략)

<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

(생략)

 

 

프로젝트를 빌드하여 apk 파일을 생성하고, 핸드폰에 설치합니다.

 

 

PUSH 발송 테스트

 

방법1)

Firebase console 페이지에 접근해서 [ 참여 > Messaging ] 메뉴로 들어갑니다.

첫번째 메세지 보내기(?) 에서 [Firebase 알림 메시지] 를 선택하고 앱을 설치한 모든 device 로 PUSH 메세지를 발송해 볼 수 있습니다.

 

 

방법2)

PHP 코드를 아래와 같이 작성 합니다.

 

<?php

$title = "제목입니다.";
$body = "내용입니다.";

$_url = 'https://fcm.googleapis.com/fcm/send';

$_header = array(
    'Content-Type: application/json',
    'Authorization: key=서버 키' // Firebase console > 프로젝트 설정 > 클라우드 메시징에서 '서버 키' 를 복사하여 입력합니다.
);

$_data = array(
    'to' => '사용자 토큰', // 앱에서 출력된 (서버로 전송한) 토큰을 입력합니다.
    'notification' => array( // 앱이 백그라운드 또는 실행중이지 않을때 제목과 내용
        'title' => $title,
        'body' => $body
    ),
    'data' => array( // 앱이 실행중일때 제목과 내용 (내용을 보려면 앱 소스에서 코드를 추가해주세요)
        'title' => $title,
        'body' => $body
    )
);
$_param = json_encode($_data);

$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, $_url );
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlObj, CURLOPT_SSLVERSION, 1);
curl_setopt($curlObj, CURLOPT_POST, true);
curl_setopt($curlObj, CURLOPT_HEADER, false);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, $_header);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $_param);
$response = curl_exec($curlObj);

$_json = array();
$_json = json_decode($response, true);
curl_close($curlObj);
?>

 

소스는 이와 같으며 PHP 파일을 실행하여 token 으로 지정한 특정 device 로 PUSH 메세지를 발송할 수 있습니다.

 

반응형

댓글()

[Shell Script] MySQL 테이블 별로 백업 하기

프로그래밍/BASH SHELL|2022. 9. 8. 08:17
반응형

쉘스크립트를 이용하여 모든 데이터베이스를 테이블 별로 백업하는 방법 입니다.

파일명은 {DB명}.{테이블명}.sql 형식으로 남게 됩니다.

 

# vi mysql_backup_by_table.sh

 

#!/bin/bash

today=`date +%Y%m%d`

# 백업 디렉토리
mkdir -p /backup/${today}
cd /backup/${today}

# MySQL root 패스워드
root_pw='12345678'

# 1) 모든 DB 백업
list=`echo "show databases;" |mysql -uroot -p"$root_pw"`

# 2) 선택한 DB 만 백업 (개행 \n 으로 구분)
#list=`echo -e "mysql\nmonitor\nsysdocu"`

for db in $list;
do
    table_list=`echo "show tables" |mysql -uroot -p"$root_pw" $db`
    for table in $table_list;
    do
        mysqldump -uroot -p"$root_pw" $db $table > ${db}.${table}.sql
        #tar cvzf ${db}.${table}.tar.gz ${db}.${table}.sql --remove-files # 압축 보관 및 원본 삭제
    done
done

 

# chmod 700 mysql_backup_by_table.sh

 

실행

# sh mysql_backup_by_table.sh

 

 

반응형

댓글()

PHP 에서 SQL Injection 방지 쿼리 사용법 두가지 (bind_param, PDO)

프로그래밍/PHP|2022. 8. 30. 11:25
반응형

PHP 에서는 MySQL DB 데이터 입력 또는 조회시 SQL Injection 공격을 막기 위한 방법으로

bind_param 또는 PDO 방식을 사용 할 수 있습니다.

 

 

1. bind_param 사용하기

 

1) INSERT, UPDATE, DELETE

값을 출력하지 않아도 되는 경우 아래와 같은 코드를 사용 합니다.

<?php
$DB_HOST = "localhost";
$DB_USER = "sysdocu";
$DB_PASSWORD = "12345678";
$DB_NAME = "test";

// DB 연결
$conn = mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);

// 쿼리 준비
$stmt = $conn->prepare("INSERT INTO item (id, itemA, itemB) VALUES (?, ?, ?)");

// 데이터 준비
$id = "hero";
$itemA = "sword";
$itemB = "shield";

// 데이터 바인딩
$stmt->bind_param('sss', $id, $itemA, $itemB); // 대체될 데이터 세개 (하단 '참고' 확인)

// 쿼리 실행
$stmt->execute();

// 연결 종료
$stmt->close();
$conn->close();
?>

* 참고 : 바인딩 할때 변수 데이터 형식을 정의 하게 되는데, 아래 네가지 종료가 있습니다.

i : 정수

s : 문자열

d : double

b : BLOB

 

2) SELECT

값을 출력하는 경우 아래와 같은 코드를 사용 합니다.

<?php
$DB_HOST = "localhost";
$DB_USER = "sysdocu";
$DB_PASSWORD = "12345678";
$DB_NAME = "test";

// DB 연결
$conn = mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);

// 쿼리 준비
$stmt = $conn->prepare("SELECT * FROM item WHERE id=? or id=?");

// 데이터 준비
$var1 = "hero";
$var2 = "hero2";

// 데이터 바인딩
$stmt->bind_param('ss', $var1, $var2); // 대체될 데이터 두개

// 쿼리 실행
$stmt->execute();

// 모든 행의 결과를 출력
$result = $stmt->get_result();
while ($data = $result->fetch_assoc()) {
    echo $data['id'] . " / " . $data['itemA'] . " / " . $data['itemB'] . "<br>";
}

// 연결 종료
$stmt->close();
$conn->close();
?>

 

 

2. PDO 사용하기

 

1) INSERT, UPDATE, DELETE

값을 출력하지 않아도 되는 경우 아래와 같은 코드를 사용 합니다.

<?php
$DB_HOST = "localhost";
$DB_USER = "sysdocu";
$DB_PASSWORD = "12345678";
$DB_NAME = "test";

// DB 연결
$pdo = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME", $DB_USER, $DB_PASSWORD);

//쿼리 준비
$stmt = $pdo->prepare("INSERT INTO item (id, itemA, itemB) VALUES (:id, :itemA, :itemB)");

// 데이터 바인딩
$stmt->bindValue(":id", "hero");
$stmt->bindValue(":itemA", "sword");
$stmt->bindValue(":itemB", "shield");

// 쿼리 실행
$stmt->execute();

// 연결 종료
$stmt->close();
$pdo->close();
?>

 

2) SELECT

값을 출력하는 경우 아래와 같은 코드를 사용 합니다.

<?php
$DB_HOST = "localhost";
$DB_USER = "sysdocu";
$DB_PASSWORD = "12345678";
$DB_NAME = "test";

// DB 연결
$pdo = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME", $DB_USER, $DB_PASSWORD);

//쿼리 준비
$stmt = $pdo->prepare("SELECT * FROM item WHERE id=:id");

// 데이터 바인딩
$stmt->bindValue(":id", "hero");

// 쿼리 실행
$stmt->execute();

// 모든 행의 결과를 출력 (한개의 행 또는 한개의 컬럼 등 가져오는 방식은 추가 검색 권고)
$stmt->setFetchMode(PDO::FETCH_ASSOC);  // 추가 설명 아래 '참고' 확인
while ($row = $stmt->fetch()) {
    echo $data['id'] . " / " . $data['itemA'] . " / " . $data['itemB'] . "<br>";
}

// 연결 종료
$stmt->close();
$pdo->close();
?>

* 참고 : 데이터 출력 방식

fetch(PDO::FETCH_BOTH) - 숫자 인덱스와 명명된 인덱스가 있는 배열 입니다.
fetch(PDO::FETCH_ASSOC) - 행은 명명된 인덱스가 있는 배열입니다. ex) $row['itemA']
fetch(PDO::FETCH_NUM) - 행은 숫자 인덱스가 있는 배열입니다. ex) $row[0]

 

 

반응형

댓글()

안드로이드 알람 생성 2가지 방법 (Android Notifications Tutorial with Examples)

프로그래밍/ANDROID|2022. 7. 18. 12:13
반응형

아래 예제는 Notification 두 가지 방법을 다루고 있습니다.

1. 진동 및 알림 메세지가 전면 상단에 출력되며, 상태바에서도 아이콘으로 나타나는 방법

2. 진동 및 알림 메세지 없이 맨 위 상태바에서만 조용히 아이콘으로 나타나는 방법

 

 

아래는 원문 출처를 따라하며 요약한 내용입니다.

[출처] https://o7planning.org/10427/android-notification

==================================================

 

 

1. Empty Activity 로 프로젝트를 생성합니다.

 

 

2. 알림 메세지에 사용할 이미지 파일 두개를 생성합니다.

drawable/icon_notify1.png

drawable/icon_notify1.png

 

 

3. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:ems="10"
        android:hint="Title"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_message"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:ems="10"
        android:hint="Message"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_title" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:text="Send on Channel 1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_message" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="23dp"
        android:text="Send On Channel 2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

4. NotificationApp.java

package org.o7planning.notificationbasicexample;

import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

public class NotificationApp extends Application  {

    public static final  String CHANNEL_1_ID = "channel1";
    public static final  String CHANNEL_2_ID = "channel2";

    @Override
    public void onCreate() {
        super.onCreate();

        this.createNotificationChannels();
    }

    private void createNotificationChannels()  {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel1 = new NotificationChannel(
                    CHANNEL_1_ID,
                    "Channel 1",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel1.setDescription("This is channel 1");

            NotificationChannel channel2 = new NotificationChannel(
                    CHANNEL_2_ID,
                    "Channel 2",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel1.setDescription("This is channel 2");


            NotificationManager manager = this.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel1);
            manager.createNotificationChannel(channel2);
        }
    }
}

 

5. AndroidManifest.xml

<application
        android:name=".NotificationApp"
        ....
>
...
</application>

 

6. MainActivity.java

package org.o7planning.notificationbasicexample;

import android.app.Notification;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;


public class MainActivity extends AppCompatActivity {

    private NotificationManagerCompat notificationManagerCompat;

    private EditText editTextTitle;
    private EditText editTextMessage;

    private Button button1;
    private Button button2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.editTextTitle = (EditText) this.findViewById(R.id.editText_title);
        this.editTextMessage = (EditText) this.findViewById(R.id.editText_message);

        this.button1 = (Button) this.findViewById(R.id.button1);
        this.button2 = (Button) this.findViewById(R.id.button2);

        this.button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                sendOnChannel1(  );
            }
        });

        this.button2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                sendOnChannel2(  );
            }
        });

        //
        this.notificationManagerCompat = NotificationManagerCompat.from(this);
    }


    private void sendOnChannel1()  {
        String title = this.editTextTitle.getText().toString();
        String message = this.editTextMessage.getText().toString();

        Notification notification = new NotificationCompat.Builder(this, NotificationApp.CHANNEL_1_ID)
                .setSmallIcon(R.drawable.icon_notify1)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .build();

        int notificationId = 1;
        this.notificationManagerCompat.notify(notificationId, notification);
    }

    private void sendOnChannel2()  {
        String title = this.editTextTitle.getText().toString();
        String message = this.editTextMessage.getText().toString();

        Notification notification = new NotificationCompat.Builder(this, NotificationApp.CHANNEL_2_ID)
                .setSmallIcon(R.drawable.icon_notify2)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setCategory(NotificationCompat.CATEGORY_PROMO) // Promotion.
                .build();

        int notificationId = 2;
        this.notificationManagerCompat.notify(notificationId, notification);
    }
}

 

빌딩 이후 apk 파일을 설치, 어플을 실행하면 두 가지 예제의 알림 방식을 구분할 수 있습니다.

 

[출처] https://o7planning.org/10427/android-notification

반응형

댓글()

[C/C++] int 를 char 또는 const char* 로 변환하기

프로그래밍/C, C++|2022. 6. 30. 13:13
반응형

숫자 뒤에 0 을 붙이면 문자로 인식합니다.

 

const int pos = 100;

const char* charpos = pos+"0";

 

반응형

댓글()

PHP 날짜 비교하기

프로그래밍/PHP|2022. 4. 13. 10:20
반응형

일반 변수에 들어있는 날짜 텍스트로는 비교가 안됩니다. 아래와 같이 strtotime 함수를 이용해 비교 가능하도록 해주세요.

아래는 사용 예제입니다.

 

<?PHP

// 하루 전 날짜

$yesterday_time = strtotime(date("Y-m-d H:i:s", strtotime("-1 day")));

 

// 임의의 날짜

$tmp_time = strtotime("2022-04-13 10:00:00");

 

// 비교하기

if ($yesterday_time <= $tmp_time) {

    echo "임의의 날짜가 더 나중입니다.";

} else {

    echo "하루 전 날짜가 더 나중입니다.";
}

?>

반응형

댓글()

[PHP] AES-256-CBC 를 이용한 암호화 및 복호화

프로그래밍/PHP|2022. 4. 11. 08:49
반응형

[코드]

<?PHP
$str = "서버나라 개발왕자";    // 전달할 문자열
$key = "server&develop";    // 암호화, 복호화 하는 부분에서 동일한 키 사용

$en_key = base64_encode(openssl_encrypt($str, 'aes-256-cbc', $key, true, str_repeat(chr(0), 16)));
echo $en_key . "<br>";

$de_key = openssl_decrypt(base64_decode($en_key), 'aes-256-cbc', $key, true, str_repeat(chr(0), 16));
echo $de_key;
?>

 

 

[결과]

eIgTU/2u8qsWmnVorxdDYwdxRN3DMfK8PThERSmkN/I=
서버나라 개발왕자

 

반응형

댓글()

PHP 에서 json 문자열을 예쁘게 출력하려면

프로그래밍/PHP|2021. 11. 11. 15:18
반응형

아래와 같이 header 에 json 타입을 명시해주고  json 문자열을 JSON_PRETTY_PRINT 옵션을 주어 decode, encode 하면 됩니다.

 

sysdocu.php

<?
header('Content-Type: application/json');    // 필수

$data = '{ "result": "success", "data":[ { "ip": "192.168.10.2", "os": "linux" }, { "ip": "192.168.10.3", "os": "windows" } ] }';

$result = json_encode(json_decode($data), JSON_PRETTY_PRINT);

echo $result;
?>

 

결과

{
    "result": "success",
    "data": [
        {
            "ip": "192.168.10.2",
            "os": "linux"
        },
        {
            "ip": "192.168.10.3",
            "os": "windows"
        }
    ]
}

 

반응형

댓글()

PHP 와 MySQL 연동 확인 소스

프로그래밍/PHP|2021. 11. 8. 13:40
반응형

아래는 MySQL 연결이 잘 되었는지 확인하는 소스 입니다.

PHP 8.0, MySQL 8.0 에서 테스트 시 정상 동작 하는것 확인했습니다.

 

# vi dbtest.php

<?php
$conn = mysqli_connect("192.168.2.10", "sysdocu", "12345678", "sysdocudb");
 
if ($conn) {
    echo "MySQL 연결 성공";
} else {
    echo "MySQL 연결 실패";
}
 
$result = mysqli_query($conn, "SELECT VERSION() AS VERSION");
$data = mysqli_fetch_assoc($result);
echo "<br>Version : " . $data['VERSION'];
?>

 

 

추가로 데이터를 가져오는 방법입니다.

한개 행의 데이터를 가져올때는 이런 식으로 사용하고,

 

$sql = "SELECT * FROM members WHERE id='$id' AND passwd='$passwd'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$name = $row['name'];

$id = $row['id'];

$passwd = $row['passwd'];

여러 행의 데이터를 가져올때는 while 문을 사용합니다.

 

$sql = "SELECT * FROM members WHERE id='$id' AND passwd='$passwd'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {

        $name = $row['name'];
        $id = $row['id'];
        // 반복 출력
        echo $name . "<br>";
        echo $id . "<br>";
}

 

 

 

반응형

댓글()

PHP에서 JSON 배열 삭제

프로그래밍/PHP|2021. 10. 15. 15:39
반응형

PHP를 사용하여 JSON 파일에서 배열을 삭제하려고합니다.

PHP를 사용하여 배열 삭제를 설정하는 방법을 잘 모르겠습니다. jQuery 측면을 처리 할 수 ​​있습니다.

프론트 엔드에서 버튼을 클릭하면 해당 배열이 삭제됩니다.

  1. <button id="harry_0123">harry_0123</button>
  2. <button id="ben_0124">ben_0124</button>
  3.  

다음은 JSON 파일의 예입니다.

  1. {
  2. "harry_0123": {
  3. "id": "0123",
  4. "name": "harry",
  5. },
  6. "ben_0124": {
  7. "id": "0124",
  8. "name": "ben",
  9. },
  10. }
  11.  

다음은 PHP 예제입니다 :

  1. <?php
  2. $json_str = file_get_contents('doc/info.json');
  3.  
  4. $json_arr = json_decode($json_str, true);
  5.  
  6. if(!$json_arr) {
  7. $json_arr = array();
  8. }
  9. $json_str_done = json_encode($json_arr, JSON_PRETTY_PRINT);
  10. file_put_contents('doc/info.json', $json_str_done);
  11.  

 

[출처] https://www.python2.net/questions-1051494.htm

 

반응형

댓글()

PHP 에서 json 형식의 다차원 배열 값 읽고 출력하기

프로그래밍/PHP|2021. 10. 5. 07:25
반응형

PHP 에서 JSON 데이터를 파싱하는 방법이다.

JSON 데이터는 Local File 을 읽어오는 것과 Web 사이트에서 해당 URL 을 읽어오는 방법이 있다.

가장 먼저 파싱해야 할 데이터 형태 파악을 하는 코드부터 살펴보고자 구글링을 했더니 관련 코드가 있어서 주석을 좀 더 추가하고 이해를 돕는 걸 첨가하여 적어둔다.

 

 <?php
// Web JSON 파일 읽어오기
$url = 'http://ip주소/getFileList.php';
$json_string = file_get_contents($url);

// Local JSON 파일 읽어오기
//$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

foreach ($R as $key => $val) {
    if(is_array($val)) { // val 이 배열이면
        echo "$key:<br/>";
        //echo $key.' (key), value : (array)<br />';
    } else { // 배열이 아니면
        echo "$key => $val <br />";
    }
}
?>

 

위 코드로 형태파악을 한 다음에 필요한 것을 파싱처리하면 된다.

 

Local JSON 파일을 읽어서 처리하는 걸 예제로 보자.

 [
    {
        "firstName": "길동",
        "lastName": "홍",
        "email": "jdhongv@gmail.com",
        "mobile": "010-1234-1111"
    },
    {
        "firstName": "민아",
        "lastName": "김",
        "email": "minakim@gmail.com",
        "mobile": "010-1234-3333"
    },
    {
        "firstName": "진주",
        "lastName": "마",
        "email": "jjmah@gmail.com",
        "mobile": "010-1234-5555"
    },
    {
        "firstName": "서영",
        "lastName": "이",
        "email": "sylee@gmail.com",
        "mobile": "010-1234-7777"
    }
]

 

<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('data.json');
$R = json_decode($json_string, true);
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.
// $R : array data



foreach ($R as $row) {
    print $row['lastName'];
    print $row['firstName'];
    print ' , ';
    print $row['email'];
    print ' , ';
    print $row['mobile'];
    print '<br />';
}
?> 

 

결과

홍길동 , jdhongv@gmail.com , 010-1234-1111
김민아 , minakim@gmail.com , 010-1234-3333
마진주 , jjmah@gmail.com , 010-1234-5555
이서영 , sylee@gmail.com , 010-1234-7777

 

조금 더 복잡한 JSON 파일을 검색한 걸 테스트한다.

{
    "name": "홍길동",
    "alias": "LInk",
    "members": [
        "소원",
        "예린",
        "은하",
        "유주",
        "신비",
        "엄지"
    ],
    "albums": {
        "EP 1집": "Season of Glass",
        "EP 2집": "Flower Bud",
        "EP 3집": "Snowflake",
        "EP 4집": "THE AWAKENING"
    }
}

 

파싱하는 코드를 두가지로 테스트해보면 print_r 에서 결과를 다르게 보여준다.

<?php
// JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R);
echo '<br />';

foreach ($R as $key => $val) {
    if(is_array($val)) {
        echo "$key:<br/>";
    } else {
        echo "$key => $val<br/>";
    }
}
?>
<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
$R = json_decode($json_string, true); //
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R); // 배열 요소를 출력해준다.
echo '<br />';
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP JSON parser sample</title>
    </head>

    <body>
        <h3 id="gname">
        <?php
            echo $R['name'];
            if (array_key_exists('alias', $R))
                printf(" (%s)", $R['alias']);
        ?>
        </h3>
        <p>멤버 구성: <span id="members">
            <?php echo implode(', ', $R['members']);?></span>
        </p>
        <h3>앨범 목록</h3>
        <ul id="albums">
        <?php
            foreach ($R['albums'] as $key => $value) {
                printf("<li>%s: %s</li>\n", $key, $value);
            }
            ?>
        </ul>
    </body>
</html>


출처: https://link2me.tistory.com/1408 [소소한 일상 및 업무TIP 다루기]

 

참고 : 배열에 배열 추가


$arrs = array();                  // 전체 배열을 준비하고
array_push($arrs, $arr)); //$arr 배열을 배열에 넣는다 (다차원 배열)

반응형

댓글()