Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

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

);


Friday, June 14, 2024

multi sort array in PHP

<?php

// Example combined data array

$combined_data = [

    ['partno' => 'B456', 'wd' => '20240613', 'qty' => 5],

    ['partno' => 'A123', 'wd' => '20240612', 'qty' => 10],

    ['partno' => 'C789', 'wd' => '20240614', 'qty' => 8],

    ['partno' => 'A123', 'wd' => '20240612', 'qty' => 15],

    ['partno' => 'B456', 'wd' => '20240613', 'qty' => 2],

];


// Generalized comparison function for multi-key sorting

function multiKeyCompare($keys) {

    return function ($a, $b) use ($keys) {

        foreach ($keys as $key) {

            if ($a[$key] < $b[$key]) return -1;

            if ($a[$key] > $b[$key]) return 1;

        }

        return 0;

    };

}


// Define the keys to sort by

$keys = ['partno', 'qty']; // First sort by 'partno', then by 'qty'


// Sort the combined data array using the generalized comparison function

usort($combined_data, multiKeyCompare($keys));


// Print the sorted array

foreach ($combined_data as $item) {

    echo "Part No: " . $item['partno'] . ", WD: " . $item['wd'] . ", QTY: " . $item['qty'] . "<br>";

}

?>

how to count rows in sqlserver -->sqlsrv_num_rows

 Example #1 sqlsrv_num_rows() example

<?php
$server
= "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );

$sql = "SELECT * FROM Table_1";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );

$row_count = sqlsrv_num_rows( $stmt );

if (
$row_count === false)
echo
"Error in retrieveing row count.";
else
echo
$row_count;
?>

Tuesday, October 31, 2023

PHP notify imageFile (from image in server)

 <?php

/*-------------line noti----------------------*/

$line_api = 'https://notify-api.line.me/api/notify';

$access_token = 'your token';


$message = 'test'; //text max 1,000 charecter

$filepath='2.jpg';

$filename = realpath($filepath);

$finfo = new \finfo(FILEINFO_MIME_TYPE);

$mimetype = $finfo->file($filename);


if (function_exists('curl_file_create')) {

$cFile = curl_file_create($filename, $mimetype, basename($filename));

} else {

$cFile = '@'.realpath($imageFile );

}


$message_data = array(

'message' => $message,

'imageFile' => $cFile

);


$result = send_notify_message($line_api, $access_token, $message_data);


echo '<pre>';

print_r($result);

function send_notify_message($line_api, $access_token, $message_data){

$headers = array('Method: POST', 'Content-type: multipart/form-data', 'Authorization: Bearer '.$access_token );


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $line_api);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_POSTFIELDS, $message_data);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);

// Check Error

if(curl_error($ch))

{

$return_array = array( 'status' => '000: send fail', 'message' => curl_error($ch) );

}

else

{

$return_array = json_decode($result, true);

}

curl_close($ch);

return $return_array;

}

echo '</pre>';


/*-------------line noti----------------------*/

?>

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, July 26, 2012

การตั้งค่า PHPMYADMIN ให้ใช้ได้จากเครื่องอื่น

H:\Xampp\phpMyAdmin\config.inc.php

for localhost only

$cfg['Servers'][$i]['auth_type'] = 'config';

for gobal
$cfg['Servers'][$i]['auth_type'] = 'cookie';