1

Hoping you can help me.

My Goal

  1. Creating a custom Like(♥) button with a counter.
  2. Store (INSERT) onclick() output value to MySQL
  3. Increment (UPDATE) stored value by one(+1)
  4. Retrieve (READ) lastest incremented value from MySQL and display on web page

What I have working

I have JavaScript outputting the value of '1' onclick.

My issue

Storing the JavaScript value on a database so it increments by 1 for every user click. I'm a bit suck with this. Any help is highly appreciated!

THE PROBLEM CODE:

HTML:

<div class="heart" id="like" onclick="onClick()">
    <span id="output"></span>
</div>

JavaScript:

// Heart Like counts
var clicks = 0;
var hasClicked = false;
    function onClick() 
    {
     if (!hasClicked) 
      {
       clicks += 1;
          document.getElementById("output").innerHTML = clicks;
          hasClicked = true; 
      };
        
    };

PHP (Connection File to DB)

<?php
//Opens connection to MySQL sever.
$severname = 'localhost';
$username = 'root';
$password = 'root';
$dbname = 'db_Portfolio';


//Creating connection to DB
$conn = mysql_connect($severname, $username, $password);

// Check connection.
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

//Status of connection. 
echo "Connected to database successfully.";
?>

MySQL:

CREATE TABLE `Like_Count` (
  `Id` int(11) NOT NULL,
  `Likes` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `Likes` (`Likes`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Andrew C. Duarte
  • 237
  • 2
  • 15

1 Answers1

0

The count table:

CREATE TABLE `Like_Count` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Like_id` int(11) NOT NULL ,
  `Like_count` int(11) NOT NULL ,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `Likes` (`Like_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

the user table :

CREATE TABLE `Like_Count` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `User_id` int(11) NOT NULL ,
  `Like_id` int(11) NOT NULL ,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

so everytime someone clicks, check in user table to see if he has clicked. If not, update the count table with the Like_id you find in the user table to get the record in count table.

You'd better do the click action by using JavaScript and using PHP for checking and database works.

jayxhj
  • 2,829
  • 1
  • 19
  • 24