PHP how to connect two players - php

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

Related

SQL/PHP Database Connection to Client Side Display

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.

PHP MySQL Update after Seconds

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."'");

Trying to reduce memory usage of script

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.

Slow code using MSQL, PHP and AJAX

I'm currently trying to learn HTML, AJAX, PHP, and MYSQL. I'm currently building a webapp just for internal use. It al seemed to work but now I'm experiencing some lag in my code using the MYSQL function.
Here's what happens:
First off all, I create some "profile images" form an sql database. trough PHP like this:
<?php
$price = 30;
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Og297", $con);
$result = mysql_query("SELECT * FROM Og297.Drinkers");
while($row = mysql_fetch_array($result))
{
$picture = $row['Picture'];
$name = $row['Name'];
$nameup= $name."up";
$namep= $name."p";
$Onbetaaldresult = mysql_query("SELECT COUNT(Betaald) AS ob FROM Og297.Bierlijst
WHERE Betaald='1' AND Name='$name'");
$Onbetaaldarray= mysql_fetch_array($Onbetaaldresult);
$Onbetaald= $Onbetaaldarray['ob'];
$Betaaldresult = mysql_query("SELECT COUNT(Betaald) AS b FROM Og297.Bierlijst
WHERE Betaald='0' AND Name='$name'");
$Betaaldarray= mysql_fetch_array($Betaaldresult);
$Betaald= $Betaaldarray['b'];
echo "<div onclick=\"addBeer('$name','$price');\" class= 'thumbnail'><img src= $picture height= '90' width= '90' alt= $name title= $name><div class= 'overlay'><span id=$nameup class='unpaid'>$Onbetaald</span><span id= $namep class='paid'>/$Betaald</span></div></div>";
}
mysql_close($con);
?>
So this shows for every user a picture div, on top of that it shows to span's with the ID's Paid and Unpaid(The app is for keeping track how much beer we've paid and how much still need to be paid). This all works :)
next I have some functions;
On is addBeer, wich ads a beer into a table, including the name of that person. This is done trough Ajax.
function addBeer (n,p)
{
$.post("AddBeer.php",{naam: n, price: p});
updateBeer(n);
}
So after having inserted the beer into the datbase, I want it to update the Paid and Unpaid span's. I do this by using updateBeer.
function updateBeer (n)
{
$.post("UpdateBeer.php",{naam: n},function(data) {
changeInfo(n,data.betaald,data.onbetaald);
},"json");
}
This returns the amount of paid and unpaid in a Json object. Those values(including the name of the person are then given to changeInfo function, wich will update the span's like this:
function changeInfo(n,b,ob)
{
window.alert("ja");
document.getElementById(n + "up").innerHTML=ob;
document.getElementById(n + "p").innerHTML="/" + b;
}
However, the info is not updated every time I click an image.. It lags behind, the beers are inserted tough, but the updating of the span's is just not happening. How come?
Thanks very much for even reading this huge question!
The problem in my code was that the AJAX request where async. Thus causing problems when the rest of the script was executed before the AJAX request was completed. The trick was to set the AJAX request to set Async to false!
Thanks!

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

Categories