Like count updated successfully. Creating a Dynamic Like Button with PHP and MySQL | Computer Science X

Creating a Dynamic Like Button with PHP and MySQL

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

in Node.JS, AWS

Page Views: 27





  1. Creating a database and table for page likes using MySQL Workbench:

    1. Create a Database:
      • Manually:

      • Open MySQL Workbench and connect to your MySQL server.
      • In the navigator panel, right-click the "schemas" tab.
      • Select "Create Schema."
      • Provide a schema name (e.g., "csx2") and click "Apply" to create the new database.

      • Creating a database and table for page likes using MySQL Workbench:

        Using Commands:

        
        
        
                  
        CREATE DATABASE csx2;
                  
                  
        This is a sample static text string to copy!
    2. Create a Table:
      • Manually:

      • Under the appropriate database in the left navigation pane, right-click "Tables" and select "Create Table..."
      • Enter the table name (e.g., "likes").
      • Add columns: "pageName" and "count" with their respective data types and any other necessary details.
      • Click "Apply" to create the table.

      • Using Commands:

        
        
        
                    
        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';
        
                  


  2. Displaying MySQL Database Values with PHP on an HTML Web Page

    To display MySQL database values on an HTML web page using PHP, follow these steps:

    1. Web Server Setup:
      • Ensure you are running a web server that supports PHP (e.g., LAMP or NginX).
    2. File Extension Change:
      • Rename your HTML file to have a .php extension instead of .php..
    3. Embed PHP Code:
      • At the top of your PHP-enabled HTML file, add the following code before your HTML content:
      • web-page.php
        
        
        
                  
        <?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);
        
        ?>
                  
                  


  3. 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.

    html-file.php
    
    
    
              
    <?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>
              
              


  4. 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.

    action-page.php
    
    
    
    
    <?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.php", 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>


  5. Updated from this point on 10 Jun 25

    Now that we have created a basic like button, we can make this more secure by using cookies to allow 1 like per user every 30 days. This should prevent people spamming the like button. Another problem we can fix is, when the like button is clicked, the browser goes off the page, runs the php script then returns to the page. We can use AJAX Javascript to allow the php script to be run without leaving the page. We can also add text to tell the user they have successfully added their like to the page.

    html-file.php
    
    
    
              
    
    <?php
    
    $servername = "ls-69e63541feb052b9743aedewdwefewff41beec29169.c5ackdewdweecp.eu-east-2.rds.amazonaws.com";
    $username = "dbmasteruser";
    $password = "EL[efeffeewf?(3K:sp%sJ9rwerfwJ(O_^";
    $database = "webdevdb";
    
              
    $con = mysqli_connect($servername, $username, $password, $database);
    $result = mysqli_query($con,"SELECT count FROM likes WHERE ID = 1");
    $data = $result->fetch_all(MYSQLI_ASSOC);
    
    $result2 = mysqli_query($con,"SELECT views FROM likes WHERE ID = 1");
    $data2 = $result2->fetch_all(MYSQLI_ASSOC);
    
    
    if(!isset($_COOKIE['not_unique1'])) {
        setcookie('not_unique1', '1', time() + (86400)); //30 days
        // Establish database connection
        $conn = new mysqli($servername, $username, $password, $database);
    
        // Check for connection errors
        if ($conn->connect_error) {
            die("Database connection failed: " . $conn->connect_error);
        }
        // SQL query to increment the like count
        $sql = "UPDATE likes SET views = views + 1 WHERE ID = 1";
    
        // Execute the query and check for errors
        if ($conn->query($sql) === TRUE) {
            echo "Like count updated successfully.";
        } else {
            echo "Error updating like count: " . $conn->error;
        }
    }
    
    ?>
    // Example HTML for PHP code positioning
    <!DOCTYPE html>
    <html lang="en-US">
    
      <head>
        <title>Example HTML code</title>
      </head>
      <body>
        <p>Example</p>
    
    
    
    <script>
    function showCustomer(x) {
    
      let result = document.getElementById("GFG");
    
      //  x.classList.toggle("btn-phoenix-success");
    
      const xhttp = new XMLHttpRequest();
      xhttp.onload = function() {
        document.getElementById("txtHint").innerHTML = this.responseText;
      }
      xhttp.open("GET", "action-page.php?");
      xhttp.send();
      result.innerHTML = "Like successfully added";
    
    
    
    }
    </script>
    
    
    
    
    <button onclick="showCustomer(this)" class="btn btn-phoenix-danger me-1 mb-1" type="button" style="color:teal;">
      <?php foreach($data as $row): ?>
        <?= htmlspecialchars($row['count']) ?>
      <?php endforeach ?>
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-hand-thumbs-up" viewBox="0 0 16 16">
          <path d="M8.864.046C7.908-.193 7.02.53 6.956 1.466c-.072 1.051-.23 2.016-.428 2.59-.125.36-.479 1.013-1.04 1.639-.557.623-1.282 1.178-2.131 1.41C2.685 7.288 2 7.87 2 8.72v4.001c0 .845.682 1.464 1.448 1.545 1.07.114 1.564.415 2.068.723l.048.03c.272.165.578.348.97.484.397.136.861.217 1.466.217h3.5c.937 0 1.599-.477 1.934-1.064a1.86 1.86 0 0 0 .254-.912c0-.152-.023-.312-.077-.464.201-.263.38-.578.488-.901.11-.33.172-.762.004-1.149.069-.13.12-.269.159-.403.077-.27.113-.568.113-.857 0-.288-.036-.585-.113-.856a2 2 0 0 0-.138-.362 1.9 1.9 0 0 0 .234-1.734c-.206-.592-.682-1.1-1.2-1.272-.847-.282-1.803-.276-2.516-.211a10 10 0 0 0-.443.05 9.4 9.4 0 0 0-.062-4.509A1.38 1.38 0 0 0 9.125.111zM11.5 14.721H8c-.51 0-.863-.069-1.14-.164-.281-.097-.506-.228-.776-.393l-.04-.024c-.555-.339-1.198-.731-2.49-.868-.333-.036-.554-.29-.554-.55V8.72c0-.254.226-.543.62-.65 1.095-.3 1.977-.996 2.614-1.708.635-.71 1.064-1.475 1.238-1.978.243-.7.407-1.768.482-2.85.025-.362.36-.594.667-.518l.262.066c.16.04.258.143.288.255a8.34 8.34 0 0 1-.145 4.725.5.5 0 0 0 .595.644l.003-.001.014-.003.058-.014a9 9 0 0 1 1.036-.157c.663-.06 1.457-.054 2.11.164.175.058.45.3.57.65.107.308.087.67-.266 1.022l-.353.353.353.354c.043.043.105.141.154.315.048.167.075.37.075.581 0 .212-.027.414-.075.582-.05.174-.111.272-.154.315l-.353.353.353.354c.047.047.109.177.005.488a2.2 2.2 0 0 1-.505.805l-.353.353.353.354c.006.005.041.05.041.17a.9.9 0 0 1-.121.416c-.165.288-.503.56-1.066.56z"/>
      </svg>
    </button>
    
    
    
    
      <span class="badge text-bg-info">Page Views: 
      <?php foreach($data2 as $row): ?>
        <?= htmlspecialchars($row['views']) ?>
      <?php endforeach ?>
      
      </span>
    
      <h5 id="GFG"></h5>
    
    
      </body>
    </html>
              
              

    As you can see above, when the like button is clicked it runs the "showCustomer()" javascript function(between this script tags). this function then runs the php script without leaving the webpage and also sends a message to the user confirming their like has been successfull

    The php code at the top of the file is loading page likes and views to display and its also


    Now create an action page php file in the same directory as you web page file. and add the following code bellow:

    action-page.php
    
    
    
              
    <?php
    
    $servername = "ls-69wefewfewfew43aeaaewfewfewfewfew9169.c5ackaqik8cp.eu-west-2.rds.amazonaws.com";
    $username = "dbmasteruser";
    $password = "EL[RxRwefewfewfewfsp%sJ9wefewf^";
    $database = "webdevbd";
    
    if(!isset($_COOKIE['not_unique12'])) {
        setcookie('not_unique12', '1', time() + (86400 * 30)); //30 days
    
        // Establish database connection
        $conn = new mysqli($servername, $username, $password, $database);
    
        // Check for connection errors
        if ($conn->connect_error) {
            die("Database connection failed: " . $conn->connect_error);
        }
    
        // SQL query to increment the like count
        $sql = "UPDATE likes SET count = count + 1 WHERE ID = 1";
    
        // Execute the query and check for errors
        if ($conn->query($sql) === TRUE) {
            echo "Like count updated successfully.";
        } else {
            echo "Error updating like count: " . $conn->error;
        }
    }
    
    // Close the database connection
    $conn->close();
    
    ?>
    
    

    each cookies name needs to be unique for every page. so you will need to create a seperate action-page.php file for every web page that has a like button.