Showing posts with label Mysql. Show all posts
Showing posts with label Mysql. Show all posts

Tuesday, May 13, 2025

mysql move data over year

 CREATE TABLE record_packing_ok_2024 LIKE record_packing_ok;


INSERT INTO record_packing_ok_2024

SELECT *

FROM record_packing_ok

WHERE YEAR(date_time) < 2025;


DELETE FROM `record_packing_ok` WHERE year(`date_time`)<2025;

Wednesday, October 9, 2024

VBA Send JSON to HTTP POST PHP

 VBA

Sub SendJsonData()

    On Error GoTo ErrorHandler


    ' Create an object for ServerXMLHTTP

    Dim xmlhttp As Object

    Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")


    ' Define the URL where the data will be sent

    Dim url As String

    url = "https://192.168.0.88/xampp/API/P1.php" ' Modify the URL accordingly


    ' Create the JSON Payload

    Dim jsonData As String

    Set ws = ThisWorkbook.Sheets("Sheet1")

    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    

   'jsonData = "{""name"":""John"",""value"":30}"

    For i = 2 To lastRow

        jsonData = "{""name"":""" & ws.Cells(i, 1).Value & """, ""value"":""" & ws.Cells(i, 2).Value & """}"

        If i < lastRow Then

            jsonData = jsonData & ","

        End If

    Next i

    


    ' Set the Method and open the connection

    xmlhttp.Open "POST", url, False


    ' Bypass SSL Certificates validation (for self-signed certificates only)

    xmlhttp.setOption 2, 13056 ' Ignore SSL certificate errors


    ' Set HTTP Header to indicate that the data is JSON

    xmlhttp.setRequestHeader "Content-Type", "application/json"


    ' Send the JSON data

    xmlhttp.send jsonData


    ' Check the status of the request

    If xmlhttp.Status = 200 Then

        MsgBox "Data sent successfully: " & xmlhttp.responseText

    Else

        MsgBox "Error: " & xmlhttp.Status & " - " & xmlhttp.statusText

    End If


    ' Close the connection

    Set xmlhttp = Nothing

    Exit Sub


ErrorHandler:

    MsgBox "Error occurred: " & Err.Description

End Sub

PHP

<?php

// ตั้งค่า Header เพื่อระบุว่าคำตอบเป็น JSON และอนุญาตการเชื่อมต่อ CORS (ถ้าจำเป็น)

header("Content-Type: application/json");

header("Access-Control-Allow-Origin: *");


// ข้อมูลการเชื่อมต่อฐานข้อมูล MySQL

$servername = "192.168.0.88"; // หรือ IP ของเซิร์ฟเวอร์ฐานข้อมูล

$username = "prapop";        // ชื่อผู้ใช้ MySQL (เปลี่ยนตามจริง)

$password = "";            // รหัสผ่านของ MySQL (เปลี่ยนตามจริง)

$dbname = "test";    // ชื่อฐานข้อมูล


// สร้างการเชื่อมต่อฐานข้อมูล

$conn = new mysqli($servername, $username, $password, $dbname);


// ตรวจสอบการเชื่อมต่อ

if ($conn->connect_error) {

    die(json_encode([

        'status' => 'error',

        'message' => 'Connection failed: ' . $conn->connect_error

    ]));

}


// ตรวจสอบว่าคำขอเป็น POST หรือไม่

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // รับข้อมูล JSON ที่ส่งมา

    $json = file_get_contents('php://input');

    

    // แปลง JSON ให้เป็น Array หรือ Object

    $data = json_decode($json, true);


    // ตรวจสอบว่าการแปลงสำเร็จหรือไม่

    if ($data === null) {

        // กรณีที่ข้อมูล JSON ไม่ถูกต้อง

        echo json_encode([

            'status' => 'error',

            'message' => 'Invalid JSON'

        ]);

    } else {

        // เข้าถึงข้อมูลที่ส่งมา

        $name = $data['name'];

        $value = $data['value'];


        // เตรียมคำสั่ง SQL สำหรับบันทึกข้อมูล

        // ตรวจสอบว่า prepare สำเร็จหรือไม่

        $stmt = $conn->prepare("INSERT INTO T1 (name, value) VALUES (?, ?)");


        if ($stmt === false) {

            die(json_encode([

                'status' => 'error',

                'message' => 'Prepare failed: ' . $conn->error

            ]));

        }


        $stmt->bind_param("si", $name, $value); // ผูกตัวแปรเพื่อป้องกัน SQL Injection


        // ตรวจสอบการบันทึกข้อมูล

        if ($stmt->execute()) {

            // สำเร็จ

            echo json_encode([

                'status' => 'success',

                'message' => 'Data inserted successfully',

                'name' => $name,

                'value' => $value

            ]);

        } else {

            // เกิดข้อผิดพลาด

            echo json_encode([

                'status' => 'error',

                'message' => 'Error inserting data: ' . $stmt->error

            ]);

        }


        // ปิด statement

        $stmt->close();

    }

} else {

    // กรณีที่ไม่ใช่คำขอแบบ POST

    echo json_encode([

        'status' => 'error',

        'message' => 'Only POST requests are allowed'

    ]);

}


// ปิดการเชื่อมต่อฐานข้อมูล

$conn->close();

?>


MYSQL

CREATE TABLE T1 (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) NOT NULL,

    value VARCHAR(255) NOT NULL

);


Tuesday, July 4, 2023

mysql plus/add all data in column

 it's effortless if you know it.


UPDATE table_name SET column_name = column_name + 1 WHERE condition;

UPDATE users SET login_count = login_count + 1 WHERE id = 1;


can use with cancat

example : 

UPDATE users SET book = concat(book," add") WHERE id = 1;


Tuesday, March 28, 2023

MOVE TABLE to new DB

 alter table my_old_db.mytable rename my_new_db.mytable


alter table boxcontrol.xbk_2023_03_24l0l08_49 rename backup.xbk_2023_03_24l0l08_49

Tuesday, November 21, 2017


##connect database
try{
$db = new PDO('mysql:host=localhost;dbname=boxcontrol;charset=utf8mb4', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
exit();
}

##execute sql string
$sql="INSERT INTO all_record (barcodeid,status,plant)
values ('$barcodeid','$status','Matco1')";
$error_check=0
try {
$affected_rows = $db->exec($sql);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
$error_check=1;
}

## delete 1 parameter Array parameter

$error_check=0
try {
$stmt = $db->prepare("DELETE FROM matco1 WHERE id=:id");
$stmt->execute(array(':id'=>$_REQUEST['id']));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
$error_check=1;
}

##execute sql select

$error_check=0
try {
$stmt = $db->query($sql);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
$error_check=1;
}

while($row = $stmt->fetch(PDO::FETCH_ASSOC))

$num_rows = $stmt->fetchColumn();

Thursday, May 11, 2017

[MySQL] วิธีคัดลอกฐานข้อมูลจาก MySQL Server ไปยัง MySQL server อีกตัว


สิ่งที่ต้องเตรียม

  • mysqldrump.exe <-- drump="" span="">
  • mysqladmin.exe <-- span="">



มาลุยกันเลย!
ผมขอสมมติ
server1 (ตัวที่ต้องการย้ายหรือคัดลอกฐานข้อมูล)
server2 (ตัวใหม่ที่ต้องการเอาข้อมูลมาลง)

ณ server2 เปิด command prompt ขึ้นมาเลยครับ แล้วพิมพ์ตาม command ด้านล่างเลยครับ

วิธีคัดลอกฐานข้อมูล MySQL ไปยัง Server อื่น กรณียังไม่ได้สร้าง database สร้าง database ก่อน

c:\Appserv\MySQL\bin\mysqladmin create {database_name}

แล้วก็

C:\AppServ\MySQL\bin>mysqldump -h server1 --user={ชื่อผู้ใช้} --password={รหัสผ่าน} {source_database_name}{table}|mysql -u{ชื่อผู้ใช้} -p{รหัสผ่าน} {target_database_name}


วิธีคัดลอกฐานข้อมูล MySQL ไปยัง Server อื่น กรณีมีฐานข้อมูลอยู่แล้ว
เพิ่มพารามิเตอร์ต่อท้าย mysqldump --no-create-info --no-create-db แล้วก็ตามด้านบนเลยครับ


credit:
http://dev.mysql.com/doc/refman/5.0/en/copying-databases.html
http://stackoverflow.com/questions/12242772/easiest-way-to-copy-a-table-from-one-database-to-another


Credit
http://it-woon.blogspot.com/2014/07/How-to-copy-mysql-database-to-another.html

Friday, June 17, 2016

Delete Duplicate data in database (MYSQL)

DELETE a
FROM tpcap_dailycheck as a, tpcap_dailycheck as b
WHERE
          (a.partno   = b.partno OR a.partno IS NULL AND b.partno IS NULL)
      AND (a.del_date = b.del_date OR a.del_date IS NULL AND b.del_date IS NULL)
      AND (a.qty = b.qty OR a.qty IS NULL AND b.qty IS NULL)
      AND a.no > b.no;