[go: up one dir, main page]

0% found this document useful (0 votes)
13 views9 pages

Serverside Paper

Uploaded by

Khaijin Lim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

Serverside Paper

Uploaded by

Khaijin Lim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

User Input Form Using GET Method

<form method="GET" action="process_form_get.php">


<label>Name:</label>
<input type="text" id="name" name="name" required>
Checkbox
<label>Interests:</label>
<input type="checkbox" id="sports" name="interests[]" value="Sports"> Sports
<input type="checkbox" id="music" name="interests[]" value="Music"> Music
<input type="checkbox" id="reading" name="interests[]" value="Reading"> Reading
User Input Form Using POST Method
<form method="POST" action="process_form_post.php">
<label>Username:</label>
<input type="text" id="username" name="username" required>
process_form_post.php
<?php
$username = $_POST['username'] ?? '';
$pswd = $_POST['pswd'] ?? '';
$address = $_POST['address'] ?? '';
$plan = $_POST['plan'] ?? '';
echo "User Inquiry (POST Method):<br>";
echo "Username: $username<br>";
echo "Password: $pswd<br>";
echo "Address: $address<br>";
echo "Internet Plan: $plan";
?>
database.php
<?php
$con = mysqli_connect("localhost","root","","product_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Registration.php
require('database.php');
if (isset($_REQUEST['username'])){
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$reg_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, reg_date)
VALUES ('$username', '".md5($password)."', '$email', '$reg_date')";
$result = mysqli_query($con,$query);
login.php
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$query = "SELECT *
FROM `users`
WHERE username='$username'
AND password='".md5($password)."'" ;
$result = mysqli_query($con,$query) or die(mysqli_error($con));
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
insert.php
<?php
include("auth.php");
require('database.php');
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$product_name =$_REQUEST['product_name'];
$price = $_REQUEST['price'];
$quantity = $_REQUEST['quantity'];
$date_record = date("Y-m-d H:i:s");
$submittedby = $_SESSION["username"];
$ins_query="INSERT into products
(`product_name`,`price`,`quantity`,`date_record`,`submittedby`)values
('$product_name','$price','$quantity','$date_record','$submittedby')";
mysqli_query($con,$ins_query)
or die(mysqli_error($con));
$status = "New Product Inserted Successfully.
</br></br><a href='view.php'>View Product Record</a>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert New Product</title>
</head>
<body>
<p><a href="dashboard.php">User Dashboard</a>
| <a href="view.php">View Product Records</a>
| <a href="logout.php">Logout</a></p>
<h1>Insert New Product</h1>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="product_name" placeholder="Enter Product Name" required
/></p>
<p><input type="number" name="price" step="0.01" min="0" placeholder="Enter Product
Price (RM)" required /></p>
<p><input type="number" name="quantity" placeholder="Enter Product Quantity" required
/></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#008000;"><?php echo $status; ?></p>
</body>
</html>
view.php
<?php
$count=1;
$sel_query="SELECT * FROM products ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
$currencySymbol = "RM";
while($row = mysqli_fetch_assoc($result)) {
?>
<tr><td align="center"><?php echo $count; ?></td>
<td align="center"><?php echo $row["product_name"]; ?></td>
<td align="center"><?php echo $currencySymbol . $row["price"]; ?></td>
<td align="center"><?php echo $row["quantity"]; ?></td>
<td align="center"><?php echo $row["date_record"]; ?></td>
<td align="center">
<a href="update.php?id=<?php echo $row["id"]; ?>">Update</a>
</td>
<td align="center">
<a href="delete.php?id=<?php echo $row["id"]; ?>" onclick="return confirm('Are you sure
you want to delete this product record?')">Delete</a>
update.php
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$id=$_REQUEST['id'];
$product_name =$_REQUEST['product_name'];
$price = str_replace('RM ', '', $_REQUEST['price']);
$quantity =$_REQUEST['quantity'];
$date_record = date("Y-m-d H:i:s");
$submittedby = $_SESSION["username"];
$update="UPDATE products set date_record='".$date_record."',
product_name='".$product_name."', price='".$price."', quantity='".$quantity."',
submittedby='".$submittedby."' where id='".$id."'";
mysqli_query($con, $update) or die(mysqli_error($con));
$status = "Product Record Updated Successfully. </br></br>
<a href='view.php'>View Updated Record</a>";
echo '<p style="color:#008000;">'.$status.'</p>';
}else {
?>
delete.php
<?php
require('database.php');
$id=$_GET['id'];
$query = "DELETE FROM products WHERE id=$id";
$result = mysqli_query($con,$query) or die ( mysqli_error($con));
header("Location: view.php");
exit();
?>
Set cookie
if ($rows == 1) {
$_SESSION['username'] = $username;
$userData = mysqli_fetch_assoc($result);
if (isset($_POST['remember_me'])) {
$cookie_name = "user";
$cookie_value = $username;
$expiration_time = time() + 60 * 60 * 24 * 30;
setcookie($cookie_name, $cookie_value, $expiration_time, "/");
}
header("Location: index.php");
exit();
} else {
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else
{
Read cookie
<?php
if (isset($_COOKIE["user"])) {
$cookie_value = $_COOKIE["user"];
echo "Welcome, " . $cookie_value . ". Your cookie is now set.";
} else {
echo "Cookie is not set!";
}
?>
Delete cookie
<?php
$cookie_name = "user";
if (isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, "", time() - 3600, "/");
echo "<h3>Cookie deleted. Click here to <a href='logout.php'>Logout</a></h3>";
} else {
echo "<h3>Cookie not found. Click here to <a href='logout.php'>Logout</a></h3>";
}
?>
Logout functionality to delete cookie
<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
session_destroy();
$cookie_name = "user";
setcookie($cookie_name, "", time() - 3600, "/");
header("Location: login.php");
exit();
?>
file_manager.php
if (isset($_POST['upload'])) {
$uploadedFileName = $_FILES['file']['name'];
$targetDirectory = "upload/";
$targetFilePath = $targetDirectory . $uploadedFileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)) {
$userInput = $_POST['user_input'];
$insertQuery = "INSERT INTO files (filename, user_input) VALUES
('$uploadedFileName', '$userInput')";
mysqli_query($con, $insertQuery) or die(mysqli_error($con));
$status = "File uploaded successfully.";
} else {
$status = "File upload failed.";
}
test_error.php
<?php
session_start();
// include("auth.php");
require('database.php');
$status = "";
if(isset($_POST['new']) && $_POST['new'] == 1) {
$message = $_REQUEST['message'];
$phone_no = $_REQUEST['phone_no'];
$email = $_REQUEST['email'];
$userId = $_SESSION['user_id'] ?? 0;
$ins_query = "INSERT INTO test_error (`message`, `phone_no`, `email`, `user_id`)
VALUES ('$message', '$phone_no', '$email', '$userId')";
mysqli_query($con, $ins_query) or die(mysqli_error($con));
$status = "Data has been inserted successfully.";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert Data - Example of Error Handling</title>
</head>
<body>
<p>
<a href="dashboard.php">User Dashboard</a> |
<a href="logout.php">Logout</a>
</p>
<h1>Example Test Error - Insert Data</h1>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="message" placeholder="Enter Your Message" required
/></p>
<p><input type="text" name="phone_no" placeholder="Enter Your Phone Number"
required /></p>
<p><input type="text" name="email" placeholder="Enter Your Email Address"
required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#008000;"><?php echo $status; ?></p>
</body>
</html>
test_error.php
if(isset($_POST['new']) && $_POST['new'] == 1) {
$message = $_REQUEST['message'];
$phone_no = $_REQUEST['phone_no'];
$email = $_REQUEST['email'];
$userId = $_SESSION['user_id'] ?? 0;
if (empty($message) || empty($phone_no) || empty($email) || $userId === 0) {
$errors = array();
if (empty($message)) {
$errors[] = "Message is required.";
}
if (empty($phone_no)) {
$errors[] = "Phone number is required.";
}
if (empty($email)) {
$errors[] = "Email address is required.";
}
if ($userId === 0) {
$errors[] = "User ID is not set properly.";
}
foreach ($errors as $error) {
echo $error . "<br>";
}
} else {
$ins_query = "INSERT INTO test_error (`message`, `phone_no`, `email`, `user_id`)
VALUES ('$message', '$phone_no', '$email', '$userId')";
mysqli_query($con, $ins_query) or die(mysqli_error($con));
$status = "Data has been inserted successfully.";
}
get_content_db.php
<?php
$con = mysqli_connect("localhost", "root", "", "dynamic_content");
$sectionQuery = "SELECT about_us, contact_us FROM info";
$sectionResult = mysqli_query($con, $sectionQuery);
if ($sectionResult) {
if (mysqli_num_rows($sectionResult) > 0) {
while ($sectionRow = mysqli_fetch_assoc($sectionResult)) {
“admin_info.php” page to manage ‘About Us’ and ‘Contact Us’
content.
<!DOCTYPE html>
<html>
<head>
<title>Admin Control Panel</title>
</head>
<body>
<div class="container admin-panel">
<h1 class="update-info-title">Update Info - Home Page</h1>
<form action="update_info.php" method="post" class="info-form">
<input type="hidden" name="new" value="1" />
<label for="about_us" class="info-label">About Us</label>
<input type="text" id="about_us" name="about_us" class="form-control"><br><br>
<label for="contact_us" class="info-label">Contact Us</label>
<textarea id="contact_us" name="contact_us" class="form
control"></textarea><br><br>
<input type="submit" value="Update Info" class="btn-primary">
</form>
</div>
</body>
</html>
update_info.php
<?php
$con = mysqli_connect("localhost", "root", "", "dynamic_content");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$aboutUs = $_REQUEST['about_us'];
$contactUs = $_REQUEST['contact_us'];
$last_updated = date("Y-m-d H:i:s");
$checkQuery = "SELECT id FROM info";
$checkResult = mysqli_query($con, $checkQuery);
if (mysqli_num_rows($checkResult) > 0) {
$updateQuery = "UPDATE info SET about_us='$aboutUs',
contact_us='$contactUs', last_updated='$last_updated'";
if (mysqli_query($con, $updateQuery)) {
$status = "Data has been updated Successfully.</br></br><a
href='index.php'>Go to About Us Page to view it</a>";
} else {
echo "Error: " . $updateQuery . "<br>" . mysqli_error($con);
}
} else {
$insertQuery = "INSERT INTO info (`about_us`, `contact_us`, `last_updated`)
VALUES ('$aboutUs', '$contactUs', '$last_updated')";
if (mysqli_query($con, $insertQuery)) {
$status = "Home Page info has been inserted Successfully.</br></br><a
href='index.php'>Go to About Us Page to view it</a>";
} else {
echo "Error: " . $insertQuery . "<br>" . mysqli_error($con);
}
}
mysqli_close($con);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Content-Presentation Separation</title>
</head>
<body>
<div class="message-container">
<?php
if (isset($status)) {
echo $status;
}
“header.php”
<!DOCTYPE html>
<html>
<head>
<title>Content-Presentation Separation</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="page-header">
<nav>
<ul>
<li><a href="#">Sample Page</a></li>
<li><a href="index.php">About Us</a></li>
<li><a href="admin_info.php">Update About Us</a></li>
</ul>
</nav>
</header>
<div class="container">
footer.php
</div>
<footer class="page-footer">
<p>© <?php echo date("Y"); ?> UCCD3243 Server-Side Web Applications
Development</p>
</footer>
</body>
</html>
index.html with ajax
<!DOCTYPE html>
<html>
<head>
<title>AJAX CRUD and Live Search</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>AJAX CRUD Application</h1>
<form id="userForm">
<input type="text" id="name" placeholder="Name">
<input type="text" id="email" placeholder="Email">
<button type="button" onclick="addUser()">Add User</button>
</form>
<table id="userTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<input type="text" id="search" placeholder="Live Search" onkeyup="liveSearch()">
<div id="searchResults">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
script.js
function addUser() {
var name = $('#name').val();
var email = $('#email').val();
$.post('server.php', { action: 'add', name: name, email: email }, function(response) {
displayUsers();
});
}
function displayUsers() {
$.get('server.php', { action: 'display' }, function(response) {
$('#userTable').html(response);
});
}
function liveSearch() {
var searchValue = $('#search').val();
$.get('server.php', { action: 'search', search: searchValue }, function(response) {
$('#searchResults').html(response);
});
}
$(document).ready(function() {
displayUsers();
});
function editUser(userId) {
$.get('server.php', { action: 'getSingleUser', id: userId }, function(response) {
var user = JSON.parse(response);
var updatedName = prompt("Enter updated name:", user.name);
var updatedEmail = prompt("Enter updated email:", user.email);
if (updatedName !== null || updatedEmail !== null) {
$.post('server.php', { action: 'edit', id: userId, name: updatedName, email:
updatedEmail }, function(response) {
displayUsers();
});
}
});
}
function deleteUser(userId) {
if (confirm("Are you sure you want to delete this user?")) {
$.post('server.php', { action: 'delete', id: userId }, function(response) {
displayUsers();
});
}
}
server.php
<?php
$con = mysqli_connect("localhost", "root", "", "ajax_demo");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}

if (isset($_GET['action']) && $_GET['action'] === 'display') {


$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["name"] . "</td><td>" . $row["email"] . "</td>
<td>
<button onclick='editUser(" . $row['id'] . ")'>Edit</button>
<button onclick='deleteUser(" . $row['id'] . ")'>Delete</button>
</td></tr>";
}
} else {
echo "<tr><td colspan='3'>No users found</td></tr>";
}
} elseif (isset($_GET['action']) && $_GET['action'] === 'search') {
$search = $_GET['search'];
$sql = "SELECT * FROM users WHERE name LIKE '%$search%' OR email LIKE
'%$search%'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["name"] . "</td><td>" . $row["email"] . "</td></tr>";
}
} else {
echo "<tr><td colspan='2'>No results found</td></tr>";
}
} elseif (isset($_GET['action']) && $_GET['action'] === 'getSingleUser') {
$userId = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = $userId";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
$user = mysqli_fetch_assoc($result);
echo json_encode($user);
} else {
echo "User not found";
}
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action']) && $_POST['action'] === 'add') {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($con, $sql)) {
echo "User added successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
} elseif (isset($_POST['action']) && $_POST['action'] === 'edit') {
$userId = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$userId";
if (mysqli_query($con, $sql)) {
echo "User updated successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
} elseif (isset($_POST['action']) && $_POST['action'] === 'delete') {
$userId = $_POST['id'];
$sql = "DELETE FROM users WHERE id=$userId";
if (mysqli_query($con, $sql)) {
echo "User deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
}
?>

You might also like