👉

PHP

​
PDO 資料庫連結

連結資料庫

try {
$Connection = new PDO('mysql:host=localhost;dbname=資料庫名稱;charset=utf8', '使用者帳號', '使用者密碼');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}

讀取資料

$Customer = $Connection->query("SELECT * FROM `表格名稱`
WHERE `Name` LIKE '查詢條件'
or `Phone` LIKE '查詢條件'")->fetchAll(PDO::FETCH_ASSOC)

編輯資料

$stmt = $Connection->prepare("UPDATE `Customer` SET `Name`=?, `Phone`=?, `Address`=?, `Remarks`=? WHERE `ID` LIKE ?")
->execute([
$_POST['Name'],
$_POST['Phone'],
$_POST['Address'],
$_POST['Remarks'],
$_POST['ID']
]);
​
if ($stmt) {
$Json['Status'] = "Ok" ;
$Json['Msg'] = $_POST['ID'] ;
} else {
$Json['Status'] = "Error" ;
$Json['Msg'] = "失敗" ;
}

創建資料

$Query = $Connection->prepare("INSERT INTO `Customer` (`ID`, `Name`, `Phone`, `Address`, `Remarks`, `Create_Time`) VALUES (?, ?, ?, ?, ?, ?)");
$Fetch = $Query->execute([
$Microtime,
$_POST['Name'],
$_POST['Phone'],
$_POST['Address'],
$_POST['Remarks'],
date('Y/m/d H:i:s')
]);
$Count = $Query->rowCount();
​
if ($Count) {
$Json['Status'] = "Ok" ;
$Json['Msg'] = $Microtime ;
} else {
$Json['Status'] = "Error" ;
$Json['Msg'] = "失敗" ;
}
JSON 陣列轉換

Json To Array

// 定義要處理的字串
$Json = '["A","B","C"]';
print_r(json_decode($Json, True));
// 輸出:Array ( [0] => "A" [1] => "B" [2] => "C")

Array To Json

// 定義要處理的字串
$Array = array("A", "B", "C");
echo json_encode($Array); // 輸出:["A","B","C"]
Count 統計陣列數量
count(array())
Preg_replace 移除括號內內容
// 定義要處理的字串
$str = '[路竹中山店] 買家取件成功';
​
// 使用 preg_replace() 函數和正規式匹配括號內內容
$pattern = '/\[(.*?)\]/';
$replacement = '';
$new_str = preg_replace($pattern, $replacement, $str);
​
// 輸出處理後的字串
echo $new_str; // 輸出:買家取件成功
Number_format 數字千分位逗號分隔函數
// 定義要處理的字串
$number = 1234.56;
​
// 英文表示法(默認)
$english_format_number = number_format($number); // 輸出:1,235
​
// 英文表示法,不帶千分位
$english_format_number = number_format($number, 2, '.', ''); // 輸出:1234.56
​
//中文最常用的表示法,千分位為',',浮點分割為'.',保留兩位浮點數
$chinese_format_number = number_format($number,2,'.',','); // 輸出:1,234.56
Foreach 陣列迴圈
foreach ($Array as $Key => $Value) {
echo $Value
}
Switch
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
最近更新 10d ago