I want to update a MySQL field after when the site was opened for X Seconds.
I get the Seconds/Time from MySQL and want to update in MySQL when the seconds are over.
I tried
sleep($adddisplaytime);
but then the site waits complete and does not run the things over first
Is there a way to run my update after some seconds when the site is opened?
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'";
Can be in PHP or MySQL
NOTE: This will do what you want, but could be exploited by someone hitting the AJAX endpoint repeatedly, you would want to build in some protections for that.
You will need an additional PHP file, the job of that PHP is to only update the db. You will need to take that update OUT of your page loading script.
Your HTML / JS / PHP for initial load
<script>
setTimeout(function() {
$.ajax('/your/ajax/endpoint.php', {
data: {
'adid': 'your id'
/*
If this is in your PHP file, you can echo the ID straight there.
Not totally recommended, but that's one way An additional /
better way is to add it to a div with a data attribute and
use jQuery to select the data off of there
*/
}
}); // Probably lots more you can do here, but in this case, for simplicity, just sending and that's it
}, 2000); // This will do a 2 second wait
</script>
Your new additional PHP file that is at /your/ajax/endpoint.php
<?php
// THIS FILE DOES THE UPDATE
$adid = $_POST['adid'];
// As mentioned by tadman in his comment.. I would use prepared statements
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = ?";
try {
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare($query1);
$sth->execute(array($adid));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
NOTE:
Again, for security's sake, you really want to consider having your first PHP script generate a unique ID (and store it in the db), that is passed to the page, and having the AJAX send that unique ID with the adid, and if the unique ID you gave is in the database only THEN would you know it's a legitimate request. Remove the unique ID from the database and do the update.
If you want to wait for some seconds after a page is opened and then run the update statement , then write the following codes on the top of the page:-
echo "<script> setTimeout(function(){}, 2000) ; </script>" ;
$query1 = mysqli_query($con, "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'");
Related
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
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
<button id="increment-counter" type="button">Increment Counter</button>
// Add a "click" event listener to the button
document
.getElementById("increment-counter")
.addEventListener("click", async () => {
// Make a PUT request to your PHP
// The `method` probably isn't important but a GET request seemed wrong
const res = await fetch("increment-counter.php", { method: "PUT" });
// Check for any errors
if (!res.ok) {
throw new Error(
`Increment counter failed: ${res.statusText} - ${await res.text()}`
);
}
// now update the current count in-place
document.querySelector("h2").textContent = (await res.json()).Count;
});
On the server-side, something like this (and I'm using PDO because it's more beginner-friendly than MySQLi)
// increment-counter.php
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
// Only allow PUT requests
http_response_code(405);
exit;
}
// Connect to your DB
$pdo = new \PDO(
'mysql:host=HOSTNAME;dbname=epiz_33276135_ducks',
'USER',
'PASSWORD',
[
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
]
);
$pdo->beginTransaction(); // atomic updates are important
try {
// Select the current Count
$count = $pdo
->query('SELECT `Count` FROM ducks WHERE ID = 1 FOR UPDATE')
->fetchColumn();
// Update your Count column
$pdo->exec('UPDATE ducks SET `Count` = `Count` + 1 WHERE ID = 1');
$pdo->commit();
// Respond with a JSON object containing the updated count
header('content-type: application/json');
echo json_encode(['Count' => $count + 1]);
exit;
} catch ($err) {
$pdo->rollBack();
throw $err;
}
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....
<?php
$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) {
$query="UPDATE ducks SET `Count`=`Count`+1";
mysqli_query( $connect, $query);
} else {
echo 'smthin weird: ' mysqli_error($result);
}
echo "<h2>$record[Count]</h2>";
echo "<a href='$_SERVER[REQUEST_URI]'>next</a>";
Once you've got this working, have a look at HTML forms.
BTW its bad practice to use reserved words (Count) for attribute names.
I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .
I'm making a website. and one of the features i want it to have is to have a simple game that connects 2 players together. my problem is I don't know how to make it so both player are in the same "room" because on room holds only 2 players.
On way i approached this is once one player joined, he gets a "wait for next player" message and waits while sending to the database that one player have joined. how do i make it keep checking for the next 3 minutes if the next player joined?
UPDATE
First here is the code so far:
<html>
<title>SiteName (test)</title>
<head>
<?php
$servername = "localhost";
$u
sername =
$password =
$dbname =
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM game');
$stmt->execute(array('gameID' => $gameID));
while($row = $stmt->fetch()) {
print_r($row);
echo "<br />\n";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
<button onclick="myFunction()" id="w">Look for Game</button><br>
<script>
function myFunction() {
var elem = document.getElementById("w").innerHTML = "Wait";
var counter = 10;
var label= document.getElementById("lbl");
var counter = 10;
var clabel= document.createElement("p");
clabel.innerHTML = "You can download the file in 10 seconds.";
var id;
label.parentNode.replaceChild(clabel, label);
id = setInterval(function() {
counter--;
if(counter < 0) {
clabel.parentNode.replaceChild(label, clabel);
clearInterval(id);
} else {
clabel.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
}
}, 1000);
}
</script>
<?php
$conn = null;
?>
</body>
</html>
Am trying to make it so that if the first player joined, he will be waiting (i have it for 10 seconds here as a test) until the other joins. the way am trying to do it is to have a field in the database will know if the a player is in that page and await the next player. I read something about long polling but not sure how to implement it for my case.
Any feed back would be helpful, Thank you
PHP is not the best language to do this in, but if you still want to do it.
Look into using Ratchet (http://socketo.me/), which is a PHP websocket library. A websocket is full duplex, meaning that a connection between the server and client is kept open. Game state and player actions can then be communicated through this.
http://socketo.me/docs/hello-world is an example you can learn from.
first you will want javascript or some client side code to handle this. as php will execute on the server side then display to the user. if you use ajax with javascript you can get the client side and server side to work together.
you will want to use a while loop, in this loop you will set a timeout.
in the while loop you can call the ajax script you want untill you get your result you want. I'm assuming you plan on making this a turn by turn game for the players. you will want a table that sets "true" to if player 1 or player 2 are in the game. if both are turn then the game begins.
Hope this logic helps
I am a math teacher who has built an online testing site for my school to use (aka, not a pro). The site has worked well but as the amount of usage at my school increases I am starting to run into memory problems (I think). After I have about 50 to 60 users simultaneously using the site the whole website begins to crash, it will come back up after a few minutes. I never have this problem with low usage. The page where students take their quiz loads 10 questions on the page, each multiple choice with 4 radio options. (Not a lot of jquery going on). Each time the user clicks an answer I am using ajax to store their answer in the database. Below is the jquery code that sends their clicks as they take the quiz.
$('input:radio').click(function(){
var questionId = $(this).parent().parent().find('.qid').val();
var answer = $(this).val();
$.ajax({
type: "POST",
url: "insertqanswerajax.php",
data: {questionId: questionId, answer: answer},
});
});
When I load system process in my cpanel I see there are 5 different processes running, each around 80 megabytes. The maximum in my php.ini is set to 540MB. If I check the page with memory_get_peak_usage() it never reads above about half a megabyte, however in the console timeline I can see the memory usage is almost up to 10 megabytes for one user (images below). What do I need to check, or what is the best way to troubleshoot the discrepancy? What could be causing the problems? I can provide more information if needed, I am just not sure what all is relevant.
Thanks ahead of time for your help.
Here is the code for the php file accessed via ajax
<?php session_start();
include('../includes/startup.php');
$questionId = $_POST['questionId'];
$answer = $_POST['answer'];
insertQuizAnswer($questionId, $userId, $answer, 1);
?>
The function called in that file:
function insertQuizAnswer($questionId, $userId, $answer, $testId){
global $DB;
$standardsHandle = $DB->prepare("INSERT INTO quizanswers (questionid, userid,answer,testid)
VALUES (:questionId,:userId, :answer, :testId)
");
$standardsHandle->bindParam(':questionId', $questionId);
$standardsHandle->bindParam(':userId', $userId);
$standardsHandle->bindParam(':answer', $answer);
$standardsHandle->bindParam(':testId', $testId);
$standardsHandle->execute();
}
And the startup file loaded on both:
<?php
if(preg_match('/(?i)msie [2-7]/',$_SERVER['HTTP_USER_AGENT']))
{
// if IE < 8
echo "My Class Progress does not Work with this version of Internet Explorer</br>
<a href='https://www.google.com/intl/en/chrome/browser/'>Click Here to Download a more modern browser</a>";
exit;
}
else
{
}
if(isset($_POST['getGrade'])){
$_SESSION['gradeLevel'] = $_POST['getGrade'];
}
if(isset($_POST['getSubject'])){
$_SESSION['subject'] = $_POST['getSubject'];
}
include_once('../functions/userfunctions.php'); //all functions
include_once('../functions/goalfunctions.php'); //all functions
include_once('../functions/modulefunctions.php'); //all functions
include_once('../functions/globalfunctions.php'); //all functions
include_once('../functions/skillfunctions.php'); //all functions
include_once('../functions/quizfunctions.php'); //all functions
include_once('../functions/practicefunctions.php'); //all functions
include_once('../functions/benchmarkfunctions.php'); //all functions
include_once('../functions/dockfunctions.php'); //all functions
include_once('../functions/dashboardfunctions.php'); //all functions
include_once('../functions/notificationfunctions.php'); //all functions
include_once('../includes/connect.php'); //connect to database
$userSubject = $_SESSION['subject'];
$userGradeLevel = $_SESSION['gradeLevel'];
$userId = $_SESSION['userId'];
if ($_SESSION['loggedIn'] == 'true'){
}
else{
header('location: ../../index.php');
die();
}
?>
Here is the connect.php file that is accessed:
try {
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
The amount memory used is dependent on ini_set('memory_limit'); This amoutn is reserved by Apache, it doesn't matter how much the script actually uses until it runs out of memory.
Is it possible to refresh a divs content only if new content is added to the database?
I'm using this for "recent posts" that appear in the side menu.
Right now the div is set refresh every 10 seconds.
Is it somehow possible to check it a new post was added to the db and then add only that posts data to the div?
I'm using MySql, php and jquery to do all of this.
Yes, you can do it by comparing the text content.
function updateHtmlContent() {
var htmlContent=$('#divToUpdate').text();
$.ajax({
type: "GET",
datatype: "text",
//php function that should give you the text back
url: 'dataBaseFunction.php',
success: function(data) {
if (htmlContent != data) {
$('#divToUpdate').text(data);
}
}
});
}
//compare and upate every 20 seconds
setInterval(updateHtmlContent(), 20000);
Hope this help!
YES IT IS POSSIBLE
The below code will get the recent photos that has been added:
AFTER THE TIMER.PHP WAS LAODED (or your wordpress blog page)
AND ONLY AFTER A NEW PHOTO IS ADDED (you can use it for recent posts, comments, or anything)
This can be used to create a live blog for example, where the user will see all the recent comments, images or posts, or everything, even if he doesn't reload the current page. And it won't consume a lot of bandwidth as the content will be reloaded ONLY IF THERE IS NEW ADDED (it will only send a tiny check in the database otherwise).
I've just finished working out a solution for that, and I have to share it with you. I was doing it for Wordpress, i needed a function that gets the photos that has been added ONLY after the user loaded the page. It could be done by simply refreshing the div every 5 seconds, but imagine if there were 20 photos, and they had to be refreshed every 5 seconds... that's a lot of MB of data. So we will refresh them ONLY when a new photo is added (you can apply it to anything, from posts to comments or users, etc.).
There are 3 PHP files: timer.php, check.php and display.php.
The timer.php will load the check.php every 5 seconds, to check if new content is added. Notice the -6 extraction from the time of the current load of check.php.
The date-time of the timer.php will be passed (by check.php?tim=**print date) through the check.php (by **display.php?timm='. $tizz .') and to the display.php, so we can use it for a reference in our database (that will be the time from where we will load all the images, if new images are added).
If any questions, just ask. It has to work for you too, as it works for me.
ENJOY! :)
Below are the 3 PHP files, just customize them for your needs:
THE TIMER.PHP (or your wordpress blog pages):
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#quotex a").load("check.php?tim=<?php print date("Y-m-d H:i:s"); ?>");
}, 5000);
});
</script>
<div id="quote"><a></a></div>
<div id="quotex"><a></a></div>
THE CHECK.PHP :
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database name") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM wp_posts WHERE post_mime_type LIKE 'image/jpeg' ORDER BY `wp_posts`.`id` DESC LIMIT 1";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
$atime = $row['post_date'];
$tizz = $_GET['tim'];
$dsff = $row['post_date'];;
$duff = date("Y-m-d H:i:s");
//convert the date-time into seconds so we can extract 6 seconds from it
$six = strtotime(date("Y-m-d H:i:s"))-6;
//convert the latest image date-time too from database so we can compare it
$sox = strtotime("$dsff");
if ($six < $sox)
{
echo '<script type="text/javascript">$(document).ready( function(){ $("#quote a").load("display.php?timm='. $tizz .'"); } ); </script>';
}
}
// Close the database connection
mysql_close();
?>
THE DISPLAY.PHP:
<?php
$tipp = $_GET["timm"];
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database name") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM wp_posts WHERE post_mime_type LIKE 'image/jpeg' AND post_date > '$tipp' ORDER BY `wp_posts`.`id` DESC LIMIT 10";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
//guid is the column where the image url is located in the wordpress database table
$atime = $row['guid'];
echo "<img src='". $atime ."' /><br />";
}
// Close the database connection
mysql_close();
?>
Yes is possible, but you need to create a method in php and use Ajax to refresh your div.
If you update your question with code I can provide an example.
I think you are probably about 90% of the way there. I assume you are using jQuery to AJAX in the content every 10 seconds (PS That seems like a lot?)
I think you could solve your problem by making the backside function start with posts after the most recent that was found.
So if your query looks like this now:
SELECT a,b,c FROM foo
You should change it to
SELECT a,b,c FROM foo WHERE id > $last_found_id
You can store last_found_id in your Javascript and send it back when you call the function. If your result set is empty then you don't have to refresh the div.
This change will also probably require that you are pre/appending to the div instead of overwriting it completely.
look at the setInterval(function, time) in javascript to make a loop each "time" (in milliseconds),
and the function $.ajax() in jQuery to pass the information to the server..
also, you have to create the new content with .html() or .append()