Information table:
The Link MY Class | https://bbs.csdn.net/forums/ssynkqtd-04 |
---|---|
The Link of Requirement of This Assignment | https://bbs.csdn.net/topics/617378696 |
The Aim of This Assignment | Create a front and back end separation calculator |
MU STU ID and FZU STU ID | 21125139_832101109 |
This blog from the pre-planning design to the later code implementation, detailed introduction of how to use JS and PHP to make the front and back ends separated web calculator.
This web calculator can implement addition, subtraction, multiplication, division, clearing, exponentiation, trigonometry, read from the back-end database and a few other functions.
Content
I. Introduction
web interface:
This calculator can perform basic mathematical operations, including addition, subtraction, multiplication, and division. It also supports exponential operations (^) and trigonometric functions (sin, cos, tan). The user can enter the number and operator by clicking the button, and then press the equal button to perform the calculation. Most important of all, we can use the ans button to return the previous calculation result, and view the history to read the last ten string formula and the corresponding calculation result.
II. PSP form
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
---|---|---|
Planning | ||
• Estimate | 50 | 60 |
Development | ||
• Analysis | 360 | 450 |
• Design Spec | 10 | 10 |
• Design Review | 20 | 20 |
• Coding Standard | 10 | 20 |
• Design | 40 | 40 |
• Coding | 300 | 400 |
• Code Review | 20 | 10 |
• Test | 30 | 45 |
Reporting | ||
• Test Report | 60 | 90 |
• Size Measurement | 5 | 5 |
• Postmortem & Process Improvement Plan | 10 | 10 |
Sum | 915 | 1160 |
This helps us track the progress of the project and ensure that it proceeds according to plan.
III. Description of problem-solving ideas
Defining Functional Requirements:
We have already completed the front-end calculator page in the last assignment. To implement read from the back-end database, we need to select and learn the back-end language. There are many kinds of back-end languages, some of which are fast to get started, while others take a long time to get started. In limited time, and because I often use idea programming, I choose PHP which is easy to get started. To use the database, I chose MySQL directly, because I had learned MySQL before, and MySQL is easy to use.
PHP:
PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed primarily for web development, especially for embedding in HTML. PHP’s syntax is influenced by the C language and incorporates features from Java, Perl, and other programming languages, resulting in its unique syntax. It continuously evolves and improves upon the foundations of these languages, including the introduction of object-oriented programming features inspired by Java.
The primary goal of PHP is to enable developers to rapidly create high-quality web sites. This language is widely used in the field of web development, providing a rich set of features and libraries for tasks such as database integration, file operations, and communication with various network protocols. PHP’s syntax is typically embedded within HTML, allowing developers to seamlessly blend dynamic content (generated by PHP) with static content (HTML).
MySQL:
MySQL is an open-source relational database management system (RDBMS) widely used for data storage and management in various applications and websites. It offers high performance, scalability, cross-platform compatibility, robust security features, supports SQL query language, and provides transaction support and replication mechanisms, making it a powerful database solution. Due to its open-source and free nature, MySQL is favored by developers and organizations, making it the preferred tool for building reliable and efficient data storage systems.
Navicat is a commercial database management and development tool that provides a graphical user interface (GUI) for managing and working with various relational databases. It is available for multiple database systems and is commonly used by database administrators, developers, and data analysts for tasks related to database design, management, and development.
IV. Design and implementation process
-
Database Setup:
Create a MySQL database to store calculation history.
Create a table to store the history with columns for id (auto-increment), formula (string formula), and result (calculation result). -
HTML Structure:
Create an HTML page for the calculator. Your HTML should include an input field for displaying the current expression, buttons for numbers and operations, an “ans” button, and a history display area. -
JavaScript:
Create JavaScript functions to handle button clicks and AJAX requests to the PHP backend.
When a button is clicked (e.g., a number, operator, “ans,” or “equals”), update the input field to reflect the button’s value.
When the “ans” button is clicked, fetch the last result from the server and append it to the current expression.
When the “equals” button is clicked, evaluate the expression, save it to the database, and display the result. -
PHP Backend:
Create a PHP script that interacts with the MySQL database and handles AJAX requests from the JavaScript.
When the “ans” button is clicked, fetch the last result from the database.
When the “equals” button is clicked, evaluate the expression and save it to the database.
When the history button is clicked, retrieve the last ten history entries from the database.
Web Calculator Flowchart
This flowchart illustrates the disign and operation of the web calculator code.
V. Code description
Detailed code:
1. JavaScript code:
Use JavaScript to implement the calculator’s business logic. First, retrieve the attributes of the ‘button’ elements. Based on the different attributes of the ‘button’ elements, execute different business logic. If the attribute of the ‘button’ element is a number or an operator, display it directly in the text box. If the attribute is “=”, calculate the result and display it in the text box. If the attribute is “C,” clear the text box.
- This JavaScript code handles a button click event and makes an Ajax GET request to a backend PHP file (“get_history.php”). It retrieves JSON data from the backend and updates the HTML elements with the retrieved data.
document.getElementById('readhistory').onclick = function () {
var Ans = document.getElementById("result2");
var result = document.getElementById("result1");
var contentAsString = String(Ans.textContent);
result.innerHTML = Ans.innerHTML;
var xhr = new XMLHttpRequest();
// Configure the request, use the GET request method, and specify the URL to the backend PHP file
xhr.open("GET", "get_history.php", true);
// Send the request
xhr.send();
// Set the callback function to handle the response
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// If the request is successfully completed, process the JSON data returned by the backend
var response = JSON.parse(xhr.responseText);
for (var i = 0; i < response.length; i++) {
var recordId = "hist" + (i + 1);
var recordDiv = document.getElementById(recordId);
recordDiv.innerHTML = response[i];
}
}
};
};
- This JavaScript code assigns a click event to a “save” button. When clicked, it calculates the result of an expression, displays the result, and sends the input and output data to a PHP script (“save_result.php”) using an Ajax GET request.
// Assign a click event to the "save" button
document.getElementById('save').onclick = function () {
// Get references to input and output elements
var result = document.getElementById("result1"); // Input element
var result1 = document.getElementById("result2"); // Output element
// Calculate the result of the expression
var finalResult = calculateExpression(result.innerHTML);
// Display the result
result1.innerHTML = finalResult;
// Get the content of the input and output elements
var str1 = document.getElementById('result1').innerHTML;
var str2 = document.getElementById('result2').innerHTML;
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure and send a GET request
xhr.open('GET', `save_result.php?result1=${str1}&result2=${str2}`, true);
xhr.send();
// Set up a callback function to handle the response
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.response);
}
}
// Clear the input element
result.innerHTML = "";
};
2. PHP code:
- save_result.php
This code connects to a MySQL database, processes expression and result values from URL parameters, and inserts them into a history table.
<?php
// Connect to your MySQL database
$servername = "localhost"; // your server name
$username = "root"; // your username
$password = "123456"; // your password
$dbname = "calculator"; // your database name
// Create a new MySQLi connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get the expression and result from the URL parameters
$expression = $_GET['result1'];
$res = $_GET['result2'];
// Replace spaces with plus signs in the expression
$re_exp = str_replace(" ", "+", $expression);
// Create the final expression with the result
$final_exp = $re_exp . "=" . $res;
echo "$final_exp";
if ($conn) {
// Set character encoding to UTF-8
mysqli_query($conn, 'set names utf8');
// SQL query to insert the expression and result into the history_table
$sql = "INSERT INTO history_table(expression, result) VALUES ('$final_exp', '$res')";
// Execute the SQL query
$result = mysqli_query($conn, $sql);
} else {
echo 'Error';
}
- get_history.php
This code connects to a MySQL database, retrieves the last 10 expressions from a history table, and returns the data in JSON format.
<?php
// Connect to your MySQL database
$servername = "localhost";
$username = "root"; // your username
$password = "123456"; // your password
$dbname = "calculator"; // database name
// Create a new MySQLi connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn) {
// Set character encoding to UTF-8
mysqli_query($conn, 'set names utf8');
// SQL query to select the last 10 expressions from the history_table
$sql = "SELECT expression FROM history_table ORDER BY no DESC LIMIT 10";
// Execute the SQL query
$result = $conn->query($sql);
if ($result) {
$data = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['expression'];
}
// Encode the data as JSON and echo it
echo json_encode($data);
} else {
// No data found
echo json_encode(array("message" => "No data found"));
}
} else {
// Query execution failed
echo json_encode(array("message" => "Query failed: " . mysqli_error($conn)));
}
// Close the database connection
$conn->close();
} else {
// Database connection failed
echo json_encode(array("message" => "Database connection failed"));
}
VI. Result functions display
Demonstration of basic calculation.
Demonstration of Ans reading the history, and view the history.
Demonstration of Front-end to back-end database.
VII. Summary
Through this assignment, I learned how to use PHP to connect to the MySQL database, and then add, delete, modify and check the database. I also learned how to use ajax to store the front-end data in the database and display the back-end data in the front-end. These knowledge are very important for our future software engineering project…
This is an example of a relatively mature front end web calculator. In fact, there is a lot of room for modification in the future, and web calculators may require more functional and security considerations, as well as stricter input validation and error handling. And there are many better ways to do it, and I will continue to learn deeply to take my software programming ability to the next level.