# PHP 基本手冊 ###### tags: `程式導師` `Backend` `PHP` ## 語法特點 1. 每行結尾要加分號 `;` 2. 只要是變數,就要帶著 `$` 3. 若要印出非數字 - `var_dump($arr);` 印出變數的型態、長度 - `print_r($arr);` 跟 `var_dump` 比,少型態 ```php <?php echo "<h1>Hello World</h1>" ?> ``` | JavaScript | PHP | | ---------- | --- | | `let a = 1;` | `$a = 1;` | | `'string' + string` | `$a . $b;` | | | `echo $a . "<br>"` | | `let arr = [1, 2, 3]` | `$arr = array(1, 2, 3)` | | `arr.length` | `sizeof($arr)` | ## PHP 與 Apache 的運作(XAMPP) request → Apache(server) → PHP → HTML → Apache → response Apache 類似物流,提供溝通管道,PHP 是翻譯。 ## 隱藏資料庫帳號密碼 分為 data.php、conn.php 兩檔案。 **conn.php** 處理帳密設定與連線 ```php <? $server_name = 'localhost'; $user_name = 'yenlai'; $password = 'yenlai'; $db_name = 'yenlai'; $conn = new mysqli($server_name, $user_name, $password, $db_name); //跟資料庫連線(主機位置:localhost, 帳號, 密碼. 資料庫名稱) if (!empty($conn->connect_error)) { die('資料庫連結失敗!'); //使用 die,就會停止往下執行 } else { echo '資料庫連結成功'; } $conn->query('SET NAMES UTF8'); $conn->query('SET time_zone = "+8:00"'); ?> ``` **data.php** 處理資料 ```php <? require_once('conn.php'); // 以下寫執行 ?> ``` ## PHP 與 MySQL 指令表 ### 拿資料 1. 使用 query:`$data = $conn->query('select now() as n;')` 2. 檢查是否有拿到:`if (!$data) { die($conn->error)};` 3. 把拿到的資料拉出來:`$row = $data->fetch_assoc();` ### 一次讀取多筆資料 ```php <?php require_once('conn.php'); //引入資料庫連線設定 $data = $conn->query("SELECT id, username FROM users;"); if (!$data) { die($conn->error); } // 一次取得多筆資料,不需要一個一個 fetch // $row = $data->fetch_assoc(); // print_r($row); // $row = $data->fetch_assoc(); // print_r($row); while($row = $data->fetch_assoc()) { print_r($row); } ?> ``` ```php <?php // 連線資料庫 $server_name = 'localhost'; $username = 'huli'; $password = 'huli'; $db_name = 'huli'; $conn = new mysqli($server_name, $username, $password, $db_name); if ($conn->connect_error) { die('資料庫連線錯誤:' . $conn->connect_error); //使用 die,就會停止往下執行 } $conn->query('SET NAMES UTF8'); $conn->query('SET time_zone = "+8:00"'); // 新增資料 $username = $_POST['username']; $sql = sprintf( "insert into users(username) values('%s')", $username ); $result = $conn->query($sql); if (!$result) { die($conn->error); } // 讀取資料 $result = $conn->query("SELECT * FROM users ORDER BY id ASC;"); if (!$result) { die($conn->error); } while ($row = $result->fetch_assoc()) { echo "id:" . $row['id']; } // 修改資料 $id = $_POST['id']; $username = $_POST['username']; $sql = sprintf( "update users set username='%s' where id=%d", $username, $id ); echo $sql . '<br>'; $result = $conn->query($sql); if (!$result) { die($conn->error); } // 刪除資料 $id = $_GET['id']; $sql = sprintf( "delete from users where id = %d", $id ); $result = $conn->query($sql); if (!$result) { die($conn->error); } if ($conn->affected_rows >= 1) { echo '刪除成功'; } else { echo '查無資料'; } ?> ```