WEB DEVELOPMENT
System Administration
In this tutorial, I’ll guide you through building a dynamic webpage with a like button that increments by +1 each time a user clicks it. The button will retrieve data from a MySQL database using PHP
CREATE DATABASE csx2;
CREATE TABLE `csx2`.`likes` ( `pageName` VARCHAR(50) NULL, `count` BIGINT NOT NULL ); // Show value command in MySQL Workspace USE csx2; SELECT count FROM likes WHERE pageName = 'page1';
To display MySQL database values on an HTML web page using PHP, follow these steps:
<?php $servername = "ls-40bb213iyb2ib3i2b3i21b3b123ib12i3hb21yu3b.cpxbg8uyiago.eu-west-2.rds.amazonaws.com"; $username = "dbmasteruser"; $password = "FBE&(QYFBE&YF&(DYWY))"; $database = "csx2"; $con = mysqli_connect($servername, $username, $password, $database); $result = mysqli_query($con,"SELECT count FROM likes"); $data = $result->fetch_all(MYSQLI_ASSOC); ?>
You’ll need to loop through each item in the database (even if there’s only one item inserted) to retrieve the data. Since we have only one page, we can simply print the loop, which will display our value for pageLikes.
<?php foreach($data as $row): ?> <?= htmlspecialchars($row['count']) ?> <?php endforeach ?>
<form class="p-4 p-md-5 border rounded-3" method="POST" action="action-page.php"> <button style="color:teal"class="btn btn-phoenix-primary w-10" type="submit"><svg class="svg-inline--fa fa-heart me-2" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="heart" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M47.6 300.4L228.3 469.1c7.5 7 17.4 10.9 27.7 10.9s20.2-3.9 27.7-10.9L464.4 300.4c30.4-28.3 47.6-68 47.6-109.5v-5.8c0-69.9-50.5-129.5-119.4-141C347 36.5 300.6 51.4 268 84L256 96 244 84c-32.6-32.6-79-47.5-124.6-39.9C50.5 55.6 0 115.2 0 185.1v5.8c0 41.5 17.2 81.2 47.6 109.5z"></path></svg> <?php foreach($data as $row): ?> <?= htmlspecialchars($row['cnt']) ?> <?php endforeach ?> </button> </form>
Create an action-page.php file in the same directory as your web page. Add the code below, ensuring you replace the values with your own.
<?php $servername = "ls-4ewccecw.cpxbg8uyiago.eu-west-2.rds.amazonaws.com"; $username = "dbmasteruser"; $password = ">pfDIg0Jlwcwcecwewg?XYp{n6"; $dbname = "csx2"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; $sql = " UPDATE likes SET count = count + 1 WHERE pageName = 'page1' "; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "" . $conn->error; } header("Location: https://computersciencex.com/indexSuccess.html", true, 301); $conn->close(); ?> // Example HTML for PHP code positioning <!DOCTYPE html> <html lang="en-US"> <head> <title>Example HTML code</title> </head> <body> <p>Example</p> </body> </html>