ESP8266, Nodemcu Cara Membaca Database MySQL

By | September 28, 2018
Hello Sahabat Anak Kendali.

Pada kesempatan kali ini saya akan menulis artikel tentang Tutorial ESP8266, Nodemcu Cara Membaca Database MySQL. sebelumnya saya juga sudah menjelaskan tentang Tutorial menyimpan Data ke Database MySQL pada artikel NodeMCU, ESP8266 Cara Mengirim Data RFID ke Database yang nantinya saya akan membuat sebuah project E-MONEY dengan menggunakan ESP8266 modul NodeMCU.

dan kali ini saya akan menjelaskan rinci bagaimana membaca data Table yang ada di DATABASE MySQL oleh ESP8266 modul NodeMCU.



baiklah berikut adalah penjelasan tutorial nya.

Pertama kita membutuhkan Database sekaligus Tabel nya untuk menyimpan data, dan server yang kita gunakan hanya Localhost.

tabel yang kita butuhkan adalah dua tabel,
1. Tabel Kartu
2. Tabel User (untuk login/registrasi)

untuk itu silahkan di buat Table Database dengan Sofware XAMPP nya, lihat pada gambar berikut :

ESP8266, Nodemcu Cara Membaca Database MySQL
ESP8266, Nodemcu Cara Membaca Database MySQL

Selanjutnya kita akan membuat program file .PHP nya, silahkan bisa di COPAS di bawah ini :

Beri nama koneksi.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

 <?php

$servername = “localhost”;
$username = “root”;
$password = “”;
$database = “monitoring”;
$conn = mysqli_connect($servername, $username, $password, $database);
function query($query){
global $conn;
$hasil = mysqli_query($conn, $query);
$rows = [];
while( $row = mysqli_fetch_assoc($hasil)){
$rows[] = $row;
}
return $rows;
}

function hapus($no){
global $conn;
mysqli_query($conn, “DELETE FROM rfid WHERE no = $no”);
return mysqli_affected_rows($conn);
}
function tambah($data){
global $conn;
$idcard = htmlspecialchars($data[“idcard”]);
$value  = htmlspecialchars($data[“val”]);
$now = new DateTime();
$datenow = $now->format(“Y-m-d H:i:s”);
$query = “INSERT INTO rfid VALUES(”,’$datenow’,’$idcard’, ‘$value’)”;
mysqli_query($conn, $query);
return mysqli_affected_rows($conn);
}
function ubah($data){
global $conn;
$no = $data[“no”];
$idcard = htmlspecialchars($data[“idcard”]);
$value  = htmlspecialchars($data[“val”]);
$query = “UPDATE rfid SET  idcard = ‘$idcard’, val = ‘$value’ WHERE no = $no “;
mysqli_query($conn, $query);
return mysqli_affected_rows($conn);
}
function registrasi($data){
global $conn;
$username = strtolower(stripslashes( $data[“username”]));
$password = mysqli_real_escape_string($conn, $data[“password”]);
$password2 = mysqli_real_escape_string($conn, $data[“password2”]);
  $result = mysqli_query ($conn, “SELECT username FROM user WHERE username = ‘$username’ “);
    if (mysqli_fetch_assoc ($result) ){
  echo “
  <script>
  alert(‘Username sudah Terdaftar’);
  </script>
  “;
  return false;
  }
if ( $password !== $password2){
echo “
<script>
alert(‘Konfirmasi Password Tidak Sesuai’)
</script>
“;
return false;
}
$password = password_hash($password, PASSWORD_DEFAULT);
mysqli_query($conn, “INSERT INTO user VALUES(”, ‘$username’, ‘$password’)”);
return mysqli_affected_rows($conn);
}
function readrfid($query){
global $conn;
$hasil = mysqli_query($conn, $query);
$rows = [];
while( $row = mysqli_fetch_assoc($hasil)){
$rows[] = $row;
}
return $rows;
}
?>

Beri nama index.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
session_start();
if (!isset($_SESSION[“login”])){
header(“Location: login.php”);
exit;
}
require ‘koneksi.php’;

$kartu = query(“SELECT * FROM rfid”);
 ?>
<!DOCTYPE html>
<html>
<head>
<title>Halaman Admin</title>
</head>
<body>
<a href=”logout.php”>Logout</a>
<h1>Daftar ID Card</h1>
<a href=”tambah.php”>Tambah ID Kartu Manual</a>
<table border=”1″ cellpadding=”5″ cellspacing=”0″>
<tr>
<th>No</th>
<th>Date</th>
<th>Id Card</th>
<th>Saldo</th>
<th>Aksi</th>
</tr>
<?php $i = 1; ?> <?php foreach ( $kartu as $data ) :{
}  ?>
<tr>
<td><?= $i; ?></td>
<td><?= $data[“date”]; ?></td>
<td><?= $data[“idcard”]; ?></td>
<td><?= $data[“val”]; ?></td>
<td>
<a href=”ubah.php?no=<?= $data[“no”]; ?>”>Edit</a> |
<a href=”hapus.php?no=<?= $data[“no”]; ?>”>Hapus</a>
</td>
</tr>
<?php $i++;  ?>
<?php endforeach; ?>
</table>
</body>
</html>

Beri nama ubah.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
session_start();
if (!isset($_SESSION[“login”])){
header(“Location: login.php”);
exit;
}

require ‘koneksi.php’;
$no = $_GET[“no”];
$krt = query(“SELECT * FROM rfid WHERE no = $no”)[0];

if (isset($_POST[“submit”]))
{
if (ubah ($_POST) > 0)
{
echo “
<script>
alert(‘Kartu Berhasil di Ubah’);
document.location.href = ‘index.php’;
</script>
“;
} else
{
echo “
<script>
alert(‘Kartu Gagal DI Ubah’);
document.location.href = ‘ubah.php’;
</script>
“;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Ubah Kartu ID</title>
<style>
label{
display: block;
} </style>
</head>
<body>
<h1>Ubah ID Kartu</h1>
<form action=”” method=”post”>
<input type=”hidden” name=”no” value=”<?= $krt[“no”]; ?>”>
<ul>
<li>
<label for =”idcard”>ID Card</label>
<input type =”text” name=”idcard” id=”idcard” required=”” value=”<?= $krt[“idcard”]; ?>”>
</li>
<li>
<label for =”val”>Value</label>
<input type=”Text” name=”val” id=”val” required=”” value=”<?= $krt[“val”]; ?>”>
</li>
<li>
<button type=”submit” name=”submit”>Ubah Kartu</button> <input type=”button” value=”Cancel” onclick=”window.location.href=’index.php'” />
</li>
</ul>
</form>
</body>
</html>

Beri nama tambah.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
session_start();
if (!isset($_SESSION[“login”])){
header(“Location: login.php”);
exit;
}
require ‘koneksi.php’;

if (isset($_POST[“submit”]))
{
if (tambah ($_POST) > 0)
{
echo “
<script>
alert(‘Kartu Berhasil di Tambahkan’);
document.location.href = ‘index.php’;
</script>
“;
} else
{
echo “
<script>
alert(‘Kartu Gagal DI Tambahkan’);
document.location.href = ‘tambah.php’;
</script>
“;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Tambah Kartu ID</title>
<style>
label{
display: block;
} </style>
</head>
<body>
<h1>Tambah ID Kartu</h1>
<form action=”” method=”post”>
<ul>
<li>
<label for =”idcard”>ID Card</label>
<input type =”text” name=”idcard” id=”idcard” required=””>
</li>
<li>
<label for =”val”>Value</label>
<input type=”Text” name=”val” id=”val” required=””>
</li>
<li>
<button type=”submit” name=”submit”>Tambah Kartu</button>
</li>
</ul>
</form>
</body>
</html>

 Beri nama hapus.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
session_start();
if (!isset($_SESSION[“login”])){
header(“Location: login.php”);
exit;
}
require ‘koneksi.php’;
$no = $_GET [“no”];
if ( hapus($no)> 0){
echo “
<script>
alert(‘Kartu Berhasil di Hapus’);
document.location.href = ‘index.php’;
</script>
“;
} else {
echo “
<script>
alert(‘Kartu Gagal di Hapus’);
document.location.href = ‘index.php’;
</script>
“;
}
 ?>

Beri nama registrasi.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php

require ‘koneksi.php’;
if (isset($_POST[“register”])) {
if (registrasi($_POST) > 0) {
echo “
<script>
alert(‘User Baru Berhasil di Tambahkan’);
</script>
“;
} else
{
echo mysqli_error($conn);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Halaman Registrasi</title>
<style>
label{
display: block;
} </style>
</head>
<body>
<h1> Halaman Registrasi</h1>
<form action=”” method=”post”>
<ul>
<li>
<label for=”username”>Username :</label>
<input type=”text” name=”username” id=”username” required=””>
</li>
<li>
<label for=”password”>Password :</label>
<input type=”password” name=”password” id=”password” required=””>
</li>
<li>
<label for=”password2″>Konfirmasi Password</label>
<input type=”password” name=”password2″ id=”password2″ required=””> </li>
<li>
<button type=”submit” name=”register”>Register</button> <input type=”button” value=”Login” onclick=”window.location.href=’login.php'” />
</li>
</ul>

</form>
</body>
</html> 

Beri nama login.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
session_start();
if (isset($_SESSION[“login”])){
header(“Location: index.php”);
exit;
}
require ‘koneksi.php’;
if (isset($_POST[“login”])){
$username = $_POST[“username”];
$password = $_POST[“password”];
$hasil = mysqli_query($conn, “SELECT * FROM user WHERE username = ‘$username’ “);
if (mysqli_num_rows($hasil) === 1 ){
$row = mysqli_fetch_assoc($hasil);
if (password_verify($password, $row[“password”]) ){
$_SESSION[“login”] = true;
header(“Location: index.php”);
exit;
}
}
$error = true;
 }
?>
<!DOCTYPE html>
<html>
<head>
<title>Halaman Login</title>
<style>
label{
display: block;
} </style>
</head>
<body>
<h1>Halaman Login</h1>
<?php if (isset($error)): ?>
<p style=”color : red; font-style: italic”>Username / Password Salah</p>
<?php endif; ?>
<form action=”” method=”post”>

<ul>
<li>
<label for=”username”>Username</label>
<input type=”text” name=”username” id=”username” required=””>
</li>
<li>
<label for=”password”>Password</label>
<input type=”password” name=”password” id=”password” required=””>
</li>
<button type=”submit” name=”login”>Login</button>
<input type=”button” value=”Sign Up” onclick=”window.location.href=’registrasi.php'” />
</ul>
</form>
</body>
</html>
 

Beri nama rfidadd.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
require ‘koneksi.php’;
$now = new DateTime();
$rfid = $_GET[‘idcard’];
$value = $_GET[‘val’];
$datenow = $now->format(“Y-m-d H:i:s”);
$sql = “INSERT INTO rfid VALUES (”,’$datenow’, ‘$rfid’, ‘$value’)”;
$result = mysqli_query($conn, $sql);
if (!$result) {
die(‘Invalid query: ‘);
}
echo “<h1>THE DATA HAS BEEN SENT!!</h1>”;
mysqli_close($conn);
?>

Beri nama rfidread.php (disimpen di folder htdocs/rfid) rfid adalah folder buatan kita sendiri

<?php
require ‘koneksi.php’;
$idcard = $_GET[“idcard”];
$hasil = mysqli_query($conn, “SELECT * FROM rfid WHERE idcard = ‘$idcard’ “);
$row = mysqli_fetch_array($hasil);
echo “ID CARD :”, $row[“idcard”],” “, “Saldo :”, $row[“val”];
?>

Hasil dari semua program di atas tampak terlihat seperti gambar gambar di bawah ini :

Sekarang kita akan membuat Program untuk NODEMCU ESP8266 dengan Arduino IDE, bisa di copas dibawah ini :

/*
 * visit www.anakkendali.com
 * 2018
 *
 */

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
WiFiClient client;
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 4
#define RST_PIN 5
MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
String request_string;
const char* host = “192.168.1.4”; // ip computer yang di install xampp (Windows + R —> CMD —->ketik ipconfig
HTTPClient http;
void setup() {
  // put your setup code here, to run once:
    WiFi.disconnect();
   WiFi.begin(“KOST_RAMA”,”bayardulu500″);
    while ((!(WiFi.status() == WL_CONNECTED))){
      delay(300);
    }
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  Serial.println(“I am waiting for card…”);
}
String strID,val, data;
void loop() {
  // put your main code here, to run repeatedly:
  while (client.available()>0){
    delay(10);
    char c = client.read();
    data+=c;
  }
  if (data.length()>0){
    Serial.println(data);
    data=””;
  }

  if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
    return;
  // Serial.print(F(“PICC type: “));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  // Serial.println(rfid.PICC_GetTypeName(piccType));
  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
      piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
      piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F(“Your tag is not of type MIFARE Classic.”));
    return;
  }
//id kartu dan yang akan dikirim ke database
  strID = “”;
  for (byte i = 0; i < 4; i++) {
    strID +=
      (rfid.uid.uidByte[i] < 0x10 ? “0” : “”) +
      String(rfid.uid.uidByte[i], HEX) +
      (i != 3 ? “:” : “”);
  }

  strID.toUpperCase();
  Serial.print(“Tap card key: “);
  Serial.println(strID);
  val = “500”; // nilai kartu yang akan dikirim
//  tambah_database();
  baca_database();
  delay(1000);

}
void tambah_database()
{
   if (!client.connect(host,80)) {
      Serial.println(“Gagal Konek”);
      return;
    }
    request_string = “/rfid/rfidadd.php?idcard=”;
    request_string += strID;
    request_string += “&val=”;
    request_string += val;
    Serial.print(“requesting URL: “);
    Serial.println(request_string);
    client.print(String(“GET “) + request_string + “HTTP/1.1rn” + “Host: ” + host + “rn” + “Connection: closernrn”);
 
    unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() – timeout > 5000) {
      Serial.println(“>>> Client Timeout !”);
      client.stop();
      return;
    }
  }
}
void baca_database()
{
   if (!client.connect(host,80)) {
      Serial.println(“Gagal Konek”);
      return;
    }
    request_string = “/rfid/rfidread.php?idcard=”;
    request_string += strID;
    Serial.print(“requesting URL: “);
    Serial.print(request_string);
    client.print(String(“GET “) + request_string + ” HTTP/1.1rn” + “Host: ” + host + “rn” + “Connection: closernrn”);
 
    unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() – timeout > 5000) {
      Serial.println(“>>> Client Timeout !”);
      client.stop();
      return;
    }
  }

hasil di Serial Monitor Arduino

mungkin cukup sekian artikel kali ini, mohon untuk di bagikan artikel artikel yang ada di web ini, dan jangan lupa untuk memberi saran, masukan atau kritik di komentar  

(Visited 674 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *