I have a website where when the user clicks a canvas, he draws on it and it gets pushed into the database. And it draws for every user 10 times in one second.
setInterval(function(){
$.ajax({
url: 'data/canvasSave.php',
success: function(data) {
$('.result').html(data);
console.log(data);
imageCanvas = data;
}
});
let img = new Image();
img.src = imageCanvas;
context.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0 , 0, canvas.width, canvas.height);
}, 100);
Now I notice that this isn't the best way. But is there a good way to check for Database updates? I tried a few if statements but none of them really worked.
You can use
PHP sockets
for tracking MySQL Database changes with WebSockets.
File: index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MySQL Tracker</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/uikit.min.css" />
</head>
<body>
<div class="uk-container uk-padding">
<h2>Users</h2>
<p>Tracking users table with WebSockets</p>
<table class="uk-table">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<?php
$connection = mysqli_connect(
'localhost',
'root',
PASSWORD,
DB_NAME
);
$users = mysqli_query($connection, 'SELECT * FROM users');
while ($user = mysqli_fetch_assoc($users)) {
echo '<tr>';
echo '<td>' . $user['id'] . '</td>';
echo '<td>' . $user['name'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</body>
</html>
Next, add the PieSocket-JS WebSocket library in your HTML file with the following code:
Now, we are ready to connect to the WebSocket channel and start receiving instantaneous updates from the server. Add the following code to your index.php file to make a websocket connection.
<script>
var piesocket = new PieSocket({
clusterId: 'CLUSTER_ID',
apiKey: 'API_KEY'
});
// Connect to a WebSocket channel
var channel = piesocket.subscribe("my-channel");
channel.on("open", ()=>{
console.log("PieSocket Channel Connected!");
});
//Handle updates from the server
channel.on('message', function(msg){
var data = JSON.parse(msg.data);
if(data.event == "new_user"){
alert(JSON.stringify(data.data));
}
});
</script>
Let??�s create a file called admin.php which adds an entry to the user??�s table, every time it is visited.
<?php
$connection = mysqli_connect(
'localhost',
'root',
PASSWORD,
DB_NAME
);
mysqli_query($connection, "INSERT INTO users .....");
?>
The code snippet given above adds an entry in the users table every time its execute either via CLI or from a webserver.
Use the following PHP function to do that.
<?php
function publishUser($event){
$curl = curl_init();
$post_fields = [
"key" => "PIESOCKET_API_KEY",
"secret" => "PIESOCKET_API_SECRET",
"channelId" => "my-channel",
"message" => $event
];
curl_setopt_array($curl, array(
CURLOPT_URL => "https://PIESOCKET_CLUTER_ID.piesocket.com/api/publish",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($post_fields),
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
print_r($response);
}
$connection = mysqli_connect(
'localhost',
'root',
PASSWORD,
DB_NAME
);
mysqli_query($connection, "INSERT INTO users .....");
$payload = json_encode([
"event" => "new_user",
"data" => [
"id"=> 1,
"name"=>"Test user"]
]);
publishUser($payload);
?>
For example, in your User model under app/model/User.php add the following code block
public static function boot() {
parent::boot();
static::created(function($user) {
publishUser(json_encode($user));
});
}
import requests
import json
url = "https://CLUSTER_ID.piesocket.com/api/publish"
payload = json.dumps({
"key": "API_KEY",
"secret": "API_SECRET",
"channelId": 1,
"message": { "text": "Hello world!" }
});
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
CSS (Cascading Style Sheets) is a formal language for describing the appearance of a document written using a markup language.
It is mainly used as a means of describing, decorating the appearance of web pages written using HTML and XHTML markup languages, but can also be applied to any XML documents, such as SVG or XUL.
https://www.w3.org/TR/CSS/#css
UIkit is another popular frontend wrapper that is arguably a little underrated in terms of CSS capabilities. In addition to many features similar to those found on other popular platforms, there are several useful specialized components.
https://getuikit.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.