I’ve been starting to program in PHP, and I want to create a program that allows any visitor to click a button and have it increment a universal counter. Eg, a user clicks the button, the counter increments by 1, and you can refresh the page and that new number will have "stuck".
My thought was to use a database that would hold the current number of "clicks" and display it, then use a client-side JavaScript button to increment the database’s value. I am able to access my database and get the current number of clicks held there statically, but I’m at a loss as to having the counter be interactional. I’ve tried googling around to see how to do this in JavaScript, and the results have been minimal. Are my goals even achievable in JavaScript? Or should I use a different language to connect my server-side ops with my client-side ones?
// connects to the database using hostname, user, pass, db name
$connect = mysqli_connect('HOSTNAME','USER','PASSWORD','epiz_33276135_ducks');
if (!$connect) {
echo 'problem connecting to database';
}
//takes the query
$query = "SELECT Count,ID,AnimalName FROM ducks WHERE ID=1";
//connects result adn records it
$result = mysqli_query( $connect, $query);
$record = mysqli_fetch_assoc( $result);
if (!$result) {
echo 'smthin weird';
}
echo '<h2>'.$record['Count'].'</h2>';
From my understanding, PHP is for server-side operations, and Javascript is for client-side work. Googling hasn’t generated any answers, and I haven’t been able to find a way that can edit hte
2
Answers
Learn one language at a time. PHP in this context writes HTML so you simply need to implement a page transition – i.e. fetch new html from the server….
Once you’ve got this working, have a look at HTML forms.
BTW its bad practice to use reserved words (Count) for attribute names.
Typically, you’d have your client-side code make a request to a PHP script that increments the count and responds with the new value. You can either use a form which results in a full page load or use an asynchronous request for a more seamless experience.
On the front-end, you’d use something like this
On the server-side, something like this (and I’m using PDO because it’s more beginner-friendly than MySQLi)