Workshop Vite + React (CRUD with PHP API and MySQL)
Workshop นี้เป็นส่วนหนึ่งของรายวิชาเรียน ไว้ฝึกทบทวนและแชร์ความรู้ให้กับคนอื่น สามารถนำไปพัฒนาต่อยอดได้
- สร้างไฟล์ PHP เชื่อมต่อกับฐานข้อมูล MySQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php class DbConnect{ private $server = 'localhost'; private $dbname = 'mycompany'; private $user = 'root'; private $pass = ''; public function connect(){ try{ $conn = new PDO('mysql:host=' . $this->server .';dbname='. $this->dbname, $this->user, $this->pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch(\Exception $e){ echo "Database Error: " . $e->getMessage(); } } } ?> |
- .htaccess
1 2 3 4 5 |
RewriteEngine On # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] |
- index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<?php error_reporting(E_ALL); ini_set('display_errors',1); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: *"); header("Access-Control-Allow-Methods: *"); // echo "testing"; include 'DBConnect.php'; $objDb = new DbConnect; $conn = $objDb->connect(); $method = $_SERVER['REQUEST_METHOD']; switch($method){ case "GET": $sql = "SELECT * FROM employee"; $path = explode('/', $_SERVER['REQUEST_URI']); if(isset($path[3]) && is_numeric($path[3])){ $sql .= " WHERE id = :id"; $stmt = $conn->prepare($sql); $stmt->bindParam(':id', $path[3]); $stmt->execute(); $employees = $stmt->fetch(PDO::FETCH_ASSOC); } else{ $stmt = $conn->prepare($sql); $stmt->execute(); $employees = $stmt->fetchAll(PDO::FETCH_ASSOC); } echo json_encode($employees); break; case "POST": $employee = json_decode(file_get_contents('php://input')); $sql = "INSERT INTO employee(id, firstname, lastname, position, salary) VALUES(null, :firstname, :lastname, :position, :salary)"; $stmt = $conn->prepare($sql); $stmt->bindParam(':firstname', $employee->firstname); $stmt->bindParam(':lastname', $employee->lastname); $stmt->bindParam(':position', $employee->position); $stmt->bindParam(':salary', $employee->salary); if($stmt->execute()){ $response = ['status' => 1, 'message' => 'Record created successfully.']; } else{ $response = ['status' => 0, 'message' => 'Failed to created record.']; } echo json_encode($response); break; case "DELETE": $sql = "DELETE FROM employee WHERE id = :id"; $path = explode('/', $_SERVER['REQUEST_URI']); $stmt = $conn->prepare($sql); $stmt->bindParam(':id', $path[3]); if($stmt->execute()){ $response = ['status' => 1, 'message' => 'Delete successfully.']; } else{ $response = ['status' => 0, 'message' => 'Failed to delete record.']; } echo json_encode($response); break; case "PUT": $employee = json_decode(file_get_contents('php://input')); $sql = "UPDATE employee SET firstname = :firstname, lastname = :lastname, position = :position, salary = :salary WHERE id = :id"; $stmt = $conn->prepare($sql); $stmt->bindParam(':id', $employee->id); $stmt->bindParam(':firstname', $employee->firstname); $stmt->bindParam(':lastname', $employee->lastname); $stmt->bindParam(':position', $employee->position); $stmt->bindParam(':salary', $employee->salary); if($stmt->execute()){ $response = ['status' => 1, 'message' => 'Record updated successfully.']; } else{ $response = ['status' => 0, 'message' => 'Failed to update record.']; } echo json_encode($response); break; } ?> |
- index.css
1 2 3 4 5 6 7 8 |
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400&display=swap'); body { margin: 0; padding: 0; box-sizing: border-box; max-height: 100vh; font-family: 'Montserrat', sans - serif !important; } |
- FormEmployee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
const [inputs, setInputs] = useState([]); const navigate = useNavigate(); const handleChange = (event) => { const name = event.target.name; const value = event.target.value; setInputs((values) => ({ ...values, [name]: value })); }; const handleAddData = (event) => { event.preventDefault(); console.log(inputs); axios.post('http://localhost/react_php/employee/save', inputs) .then(function(response){ // console.log(response.data); navigate('/'); }); }; <div> <h1>Create Employees</h1> <div> <table> <tbody> <tr> <th> <label>First Name:</label> </th> <td> <input type="text" name="firstname" className="text-input" onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <th> <label>Last Name:</label> </th> <td> <input type="text" name="lastname" className="text-input" onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <th> <label>Position</label> </th> <td> <input type="text" name="position" className="text-input" onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <th> <label>Salary:</label> </th> <td> <input type="text" name="salary" className="text-input" onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <td colSpan={2}> <button onClick={handleAddData} type="button" className="btn btn-primary" > Add Data </button> </td> </tr> </tbody> </table> </div> </div> |
- UpdateEmployee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
const [inputs, setInputs] = useState([]); const navigate = useNavigate(); const { id } = useParams(); useEffect(() => { getEmployee(); }, []); function getEmployee() { axios.get(`http://localhost/react_php/employee/${id}`) .then(function (response) { setInputs(response.data); }); } const handleChange = (event) => { const name = event.target.name; const value = event.target.value; setInputs((values) => ({ ...values, [name]: value })); }; const handleUpdateData = (event) => { event.preventDefault(); // ป้องกันการโหลดหน้าเพจใหม่ axios.put(`http://localhost/react_php/employee/${id}/update`, inputs) .then(function(response){ console.log(response.data); navigate('/'); }); }; return ( <div> <h1>Update Employees</h1> <div> <table> <tbody> <tr> <th> <label>First Name:</label> </th> <td> <input type="text" name="firstname" className="text-input" value={inputs.firstname} onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <th> <label>Last Name:</label> </th> <td> <input type="text" name="lastname" className="text-input" value={inputs.lastname} onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <th> <label>Position</label> </th> <td> <input type="text" name="position" className="text-input" value={inputs.position} onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <th> <label>Salary:</label> </th> <td> <input type="text" name="salary" className="text-input" value={inputs.salary} onChange={(e) => handleChange(e)} /> </td> </tr> <tr> <td colSpan={2}> <button onClick={handleUpdateData} type="button" className="btn btn-primary" > Update Data </button> </td> </tr> </tbody> </table> </div> </div> ); |
ShoppingCart 2024 PHP8 PDO MySQL | ระบบร้านค้าออนไลน์ E-commerce
สนใจจ้างพัฒนาระบบ เขียนระบบ
ทำเว็บไซต์ รับสอนเขียนโปรแกรม
inbox มาที่เพจ หรือติดต่อ 098-373-8651
ช่องทางการชำระเงิน
เงินสด หรือ e-banking
ธนาคารกสิกรไทย
เลขบัญชี : 0951168564
ชื่อบัญชี : นายวัยวุฒิ ชุมเมืองปัก