(text) main.js
"use client";
import { useSearchParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import axios from "axios";
import {
Button,
Table,
Row,
Col,
Modal,
Container,
Form,
} from "react-bootstrap";
import * as Icon from "react-bootstrap-icons";
const Main = () => {
const searchParams = useSearchParams();
const [contactsList, setContactsList] = useState([]);
const [groupssList, setGroupsList] = useState([]);
const [showViewModal, setShowViewModal] = useState(false);
const [showUpdateModal, setShowUpdateModal] = useState(false);
const fullName = searchParams.get("fullname");
const userId = searchParams.get("userId");
const router = useRouter();
//======== contact details ===================
const [contactId, setContactId] = useState("");
const [contactName, setContactName] = useState("");
const [contactPhone, setContactPhone] = useState("");
const [contactEmail, setContactEmail] = useState("");
const [contactAddress, setContactAddress] = useState("");
const [contactGroup, setContactGroup] = useState("");
const [contactGroupId, setContactGroupId] = useState("");
const getContacts = async () => {
const url = "http://localhost/contacts-api/contacts.php";
const jsonData = { userId: userId };
const response = await axios.get(url, {
params: { json: JSON.stringify(jsonData), operation: "getContacts" },
});
setContactsList(response.data);
};
const getGroups = async () => {
const url = "http://localhost/contacts-api/groups.php";
const response = await axios.get(url, {
params: { json: "", operation: "getGroups" },
});
setGroupsList(response.data);
};
const addContact = () => {
sessionStorage.setItem("userId", userId);
router.push("/addcontact");
};
const getContactDetails = async (contactId) => {
const url = "http://localhost/contacts-api/contacts.php";
const jsonData = { contactId: contactId };
const response = await axios.get(url, {
params: {
json: JSON.stringify(jsonData),
operation: "getContactDetails",
},
});
const contact = response.data[0];
setContactName(contact.contact_name);
setContactPhone(contact.contact_phone);
setContactEmail(contact.contact_email);
setContactAddress(contact.contact_address);
setContactGroup(contact.grp_name);
setContactGroupId(contact.contact_group);
setContactId(contact.contact_id);
};
const showViewModalForm = (contactId) => {
getContactDetails(contactId);
setShowViewModal(true);
};
const showUpdateModalForm = (contactId) => {
getContactDetails(contactId);
setShowUpdateModal(true);
};
const updateContact = async() => {
const url = "http://localhost/contacts-api/contacts.php";
const jsonData = {
contactId: contactId,
contactName: contactName,
contactEmail: contactEmail,
contactPhone: contactPhone,
contactAddress: contactAddress,
contactGroupId: contactGroupId
};
const formData = new FormData();
formData.append("operation", "updateContact");
formData.append("json", JSON.stringify(jsonData));
const response = await axios({
url: url,
method: "POST",
data: formData,
});
if(response.data == 1){
getContacts();
alert("You have successfully UPDATED your contact!");
}else{
alert("UPDATE failed!");
}
}
const deleteContact = async(contactId) => {
if(confirm("Are you sure you want to delete this contact?")){
const url = "http://localhost/contacts-api/contacts.php";
const jsonData = {
contactId: contactId
};
const formData = new FormData();
formData.append("operation", "deleteContact");
formData.append("json", JSON.stringify(jsonData));
const response = await axios({
url: url,
method: "POST",
data: formData,
});
if(response.data == 1){
getContacts();
alert("You have successfully DELETED your contact!");
}else{
alert("DELETE failed!");
}
}
}
useEffect(() => {
getContacts();
getGroups();
}, []);
return (
<>
<Container>
<h1>Contacts of {fullName}</h1>
<Table striped hover>
<thead bgcolor="red">
<tr>
<th className="bg-dark text-white">Name</th>
<th className="bg-dark text-white">Address</th>
<th className="bg-dark text-white">Phone</th>
<th className="bg-dark text-white">Actions</th>
</tr>
</thead>
<tbody>
{contactsList.map((contact, index) => {
return (
<tr key={index}>
<td>{contact.contact_name}</td>
<td>{contact.contact_address}</td>
<td>{contact.contact_phone}</td>
<td>
<Icon.Eye
className="ms-3"
color="green"
style={{ cursor: "pointer" }}
onClick={() => {
showViewModalForm(contact.contact_id);
}}
/>
<Icon.Pen
className="ms-3"
color="blue"
style={{ cursor: "pointer" }}
onClick={() => {
showUpdateModalForm(contact.contact_id);
}}
/>
<Icon.Trash
className="ms-3"
color="red"
style={{ cursor: "pointer" }}
onClick={() => {
deleteContact(contact.contact_id);
}}
/>
</td>
</tr>
);
})}
</tbody>
</Table>
<div className="fixed-bottom right-0 text-end p-2">
<Button onClick={addContact}>
<Icon.PlusCircle size={25} />
</Button>
</div>
{/* ===================== VIEW MODAL ============== */}
<Modal
show={showViewModal}
onHide={() => {
setShowViewModal(false);
}}
>
<Modal.Header closeButton className="bg-success text-white">
<Modal.Title>View Record Details</Modal.Title>
</Modal.Header>
<Modal.Body>
<Table>
<tbody>
<tr>
<td>Name</td>
<td>{contactName}</td>
</tr>
<tr>
<td>Address</td>
<td>{contactAddress}</td>
</tr>
<tr>
<td>Phone</td>
<td>{contactPhone}</td>
</tr>
<tr>
<td>Email</td>
<td>{contactEmail}</td>
</tr>
<tr>
<td>Group</td>
<td>{contactGroup}</td>
</tr>
</tbody>
</Table>
</Modal.Body>
<Modal.Footer>
<Button
variant="secondary"
onClick={() => {
setShowViewModal(false);
}}
>
Close
</Button>
</Modal.Footer>
</Modal>
{/* ===================== UPDATE MODAL ============== */}
<Modal
show={showUpdateModal}
onHide={() => {
setShowUpdateModal(false);
}}
>
<Modal.Header closeButton className="bg-success text-white">
<Modal.Title>UPDATE CONTACT</Modal.Title>
</Modal.Header>
<Modal.Body>
<Table>
<tbody>
<tr>
<td>Name</td>
<td>
<Form.Control
type="text"
value={contactName}
onChange={(e) => {
setContactName(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>Address</td>
<td>
<Form.Control
type="text"
value={contactAddress}
onChange={(e) => {
setContactAddress(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>Phone</td>
<td>
<Form.Control
type="text"
value={contactPhone}
onChange={(e) => {
setContactPhone(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>Email</td>
<td>
<Form.Control
type="text"
value={contactEmail}
onChange={(e) => {
setContactEmail(e.target.value);
}}
/>
</td>
</tr>
<tr>
<td>Group</td>
<td>
<Form.Select
value={contactGroupId}
onChange={(e) => {
setContactGroupId(e.target.value);
}}
>
{groupssList.map((group,index) => {
return(
<option value={group.grp_id} key={group.grp_id}>
{group.grp_name}
</option>
)
})}
</Form.Select>
</td>
</tr>
</tbody>
</Table>
</Modal.Body>
<Modal.Footer>
<Button
variant="secondary"
onClick={() => {
setShowUpdateModal(false);
}}
>
Close
</Button>
<Button
variant="primary"
onClick={() => {
updateContact();
setShowUpdateModal(false);
}}
>
Update
</Button>
</Modal.Footer>
</Modal>
</Container>
</>
);
};
export default Main;
(text) contacts.php
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
class Contact {
function addContact($json){
//{userId:1, name:'Pitok', email:'Pitok@gmail.com', phone:'09876565434'
//address:'CDO', groupId:3}
include 'connection-pdo.php';
$json = json_decode($json, true);
$sql = "INSERT INTO tblcontacts(contact_userId, contact_name, contact_phone,
contact_email, contact_address, contact_group)
VALUES (:contact_userId, :contact_name, :contact_phone,
:contact_email, :contact_address, :contact_group)";
$stmt = $conn->prepare($sql);
$stmt->bindParam('contact_userId', $json['userId']);
$stmt->bindParam('contact_name', $json['name']);
$stmt->bindParam('contact_phone', $json['phone']);
$stmt->bindParam('contact_email', $json['email']);
$stmt->bindParam('contact_address', $json['address']);
$stmt->bindParam('contact_group', $json['groupId']);
$stmt->execute();
$returnValue = $stmt->rowCount() > 0 ? 1 : 0;
unset($conn); unset($stmt);
return json_encode($returnValue);
}
function getContacts($json){
// {userId : 1}
include 'connection-pdo.php';
$json = json_decode($json, true);
$sql = "SELECT * FROM tblcontacts
WHERE contact_userId = :userId
ORDER BY contact_name";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':userId', $json['userId']);
$stmt->execute();
$returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
unset($conn); unset($stmt);
return json_encode($returnValue);
}
function getContactDetails($json){
// {contactId : 1}
include 'connection-pdo.php';
$json = json_decode($json, true);
$sql = "SELECT a.*, b.grp_name
FROM tblcontacts a INNER JOIN tblgroups b
ON a.contact_group = b.grp_id
WHERE a.contact_id = :contactId";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':contactId', $json['contactId']);
$stmt->execute();
$returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
unset($conn); unset($stmt);
return json_encode($returnValue);
}
function updateContact($json){
//{userId:1, contactName:'Pitok', email:'Pitok@gmail.com', contactPhone:'09876565434'
//address:'CDO', groupId:3}
include 'connection-pdo.php';
$json = json_decode($json, true);
$sql = "UPDATE tblcontacts SET contact_name=:contactName,
contact_phone=:contactPhone,
contact_email=:contactEmail, contact_address=:contactAddress,
contact_group=:contactGroupId
WHERE contact_id=:contactId";
$stmt = $conn->prepare($sql);
$stmt->bindParam('contactId', $json['contactId']);
$stmt->bindParam('contactName', $json['contactName']);
$stmt->bindParam('contactPhone', $json['contactPhone']);
$stmt->bindParam('contactEmail', $json['contactEmail']);
$stmt->bindParam('contactAddress', $json['contactAddress']);
$stmt->bindParam('contactGroupId', $json['contactGroupId']);
$stmt->execute();
$returnValue = $stmt->rowCount() > 0 ? 1 : 0;
unset($conn); unset($stmt);
return json_encode($returnValue);
}
function deleteContact($json){
// {contactId : 1}
include 'connection-pdo.php';
$json = json_decode($json, true);
$sql = "DELETE FROM tblcontacts
WHERE contact_id = :contactId";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':contactId', $json['contactId']);
$stmt->execute();
$returnValue = $stmt->rowCount() > 0 ? 1 : 0;
unset($conn); unset($stmt);
return json_encode($returnValue);
}
}
//submitted by the client - operation and json
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$operation = $_GET['operation'];
$json = $_GET['json'];
}else if($_SERVER['REQUEST_METHOD'] == 'POST'){
$operation = $_POST['operation'];
$json = $_POST['json'];
}
$contact = new Contact();
switch($operation){
case "getContacts":
echo $contact->getContacts($json);
break;
case "addContact":
echo $contact->addContact($json);
break;
case "getContactDetails":
echo $contact->getContactDetails($json);
break;
case "updateContact":
echo $contact->updateContact($json);
break;
case "deleteContact":
echo $contact->deleteContact($json);
break;
}
?>
No comments:
Post a Comment