impactjs saving higscore with php and sql - javascript

Alright, so me and my buddy is creating a game and a website, he is working on the game, and i am working on the site. The game is built using the ImpactJS engine, and everything works fine and so, but the problem we have ecountered is how we should save the highscore.
Currently we got a website built, where you can log in and then play, and our idea is that after you finish the level (or when you die) you get a score, then that score gets send to the database along with the current user thats logged in. We got the function that would do that, but the problem is that we dont know how we should send the score from the javascript file, to the actuall database.
So this is how things are looking right now:
First we actually got the highscore function in the main.js
Main.js
draw: function() {
this.parent();
this.background.draw(0,0);
var x = ig.system.width/2;
var y = ig.system.height/2 - 20;
this.gameOver.draw(x - (this.gameOver.width * .5), y - 30);
var score = (this.stats.kills * 100) - (this.stats.deaths * 50);
this.instructText.draw('Total Kills: '+this.stats.kills, x, y+30,
ig.Font.ALIGN.CENTER);
this.instructText.draw('Total Deaths: '+this.stats.deaths, x, y+40,
ig.Font.ALIGN.CENTER);
this.instructText.draw('Score: '+score, x, y+50, ig.Font.ALIGN.CENTER);
this.instructText.draw('Press Spacebar To Continue.', x, ig.system.height -
10, ig.Font.ALIGN.CENTER);
}
We understand that its the +score that we have to insert into the database.
Then we got the DB class, thats going to insert the data into the database (and by the way, im working object oriented since this is a school project and we have to do it this way)
DB.php
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field) {
$values .= '?';
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
And then lastly we got the highscore class:
Highscore.php
public function create($fields = array()) {
if(!$this->_db->insert('highscores', $fields)) {
throw new Exception('There was a problem saving your score. Sorry!');
}
}
Yeah, so basicaly we dont know how we should get the +score from the external javascript file, and send it into to php...
We did do some research and found out that maybe we should use Ajax for this? Anyhow, anybody can lend a hand?

Related

Javascript browser game inventory system, checking if item is in characters JSON file

I'm new to programming and I'm learning by coding a simple incremental game.
Currently I am working out the inventor system.
I have a cooking skill in the game with a script that will take raw items and either cook or burn them based on chance.
I'm now trying to work out an inventory system to hold the items after the action.
I have a character JSON file (linked to a firebase UID)
{
"character":[
{
"Username" : "Tester01",
"cooklvl" : "1",
"cookxp" : "0"
}
],
"items" :[
{
"rf0000" : 0,
"rf0001" : 0,
"rf0002" : 0,
"rf0003" : 0,
"rf0004" : 0,
"rf0005" : 0,
"rf0006" : 0,
"rf0007" : 0
}
]
}
I want to add items to be stored here by ID using PHP to post them to my file server.
<?php
$cookitem = $_POST['cookitem'];
$a = "../json/";
$b = $_POST['uid'];
$c = ".json";
$filename = $a.$b.$c;
$json_object = file_get_contents($filename);
$data = json_decode($json_object, true);
$data['cookitem'] = ++$cookitem;
$json_object = json_encode($data, JSON_NUMERIC_CHECK);
file_put_contents($filename, $json_object);
?>
I have this currently but I don't want to have to add the items all at once and adjust quantity. I want to add and remove them dynamically with PHP.
So I would need to check something along the lines of: Does item"RF0051" exist in playerdata.json?
If no add it and set quantity to 1.
If it does exist add 1 to the quantity.
How could I go about doing this in php? As well, is there a better way I could be going about this? The end goal is to have a fairly large amount of items. Am I shooting myself in the foot by pushing to JSON in terms of growth and server resources?
If you know what string to compare with, you can save it in a variable $yourString and then check with an if-statement if it exists:
<?php
$yourString = strtolower("RF0051");
$json_object = file_get_contents($filename);
$data = json_decode($json_object, true);
if($data['items'][$yourString] != null){
//It exists
}
?>

Change PHP variable using javascript or AJAX on the same page

I know this question has been asked alot of times, but I think in my case, I'm dealing with something different, or better saying, I need something different.
I'm using an open source that works as appointments booking but unfortunately, the client can choose the service and not the duration of it. I can recreate the same service by manually adding it more times with different minutes length but that way, in the dropdown menu, would be present alot of options and that's not what I'm looking for as a workaround.
So, what I thought of, was using a dropdown to select the time, and based on that selection, on the services dropdown menu, would show the ONLY the corresponding ones based on time.
THe site looks like this:
site
What I'm looking for, is that whenever I select the nr of hours... I ONLY GET the services that are part of that hour and not all of them.
I'm ok with using a button that refreshes the page as far as that works, but I can't create another file that then redirects here.
This is the part of the code interested in that:
<select id="select-service" class="col-xs-12 col-sm-4 form-control">
<?php
// Group services by category, only if there is at least one service with a parent category.
$has_category = FALSE;
foreach($available_services as $service) {
if ($service['category_id'] != NULL) {
$has_category = TRUE;
break;
}
}
if ($has_category) {
$grouped_services = array();
foreach($available_services as $service) {
if ($service['category_name'] == '2 HOURS' || $service['category_name'] == '1 HOUR' || $service['category_name'] == '3 HOURS') {
if (!isset($grouped_services[$service['category_name']])) {
$grouped_services[$service['category_name']] = array();
}
$grouped_services[$service['category_name']][] = $service;
}
}
// We need the uncategorized services at the end of the list so
// we will use another iteration only for the uncategorized services.
$grouped_services['uncategorized'] = array();
foreach($available_services as $service) {
if ($service['category_id'] == NULL) {
$grouped_services['uncategorized'][] = $service;
}
}
foreach($grouped_services as $key => $group) {
$group_label = ($key != 'uncategorized')
? $group[0]['category_name'] : 'Uncategorized';
if (count($group) > 0) {
echo '<optgroup label="' . $group_label . '">';
foreach($group as $service) {
echo '<option value="' . $service['id'] . '">'
. $service['name'] . '</option>';
}
echo '</optgroup>';
}
}
} else {
foreach($available_services as $service) {
echo '<option value="' . $service['id'] . '">' . $service['name'] . '</option>';
}
}
?>
</select>
I only use a single AJAX function for my platform. Below is a minimal example:
function ajax(method,url,param_id_container_pos,id_container)
{
var xhr = new XMLHttpRequest();
xhr.open(method,url,true);
xhr.onreadystatechange = function()
{
if (xhr.readyState=='4')
{
var type = xhr.getResponseHeader('content-type').split('/')[1];
if (method=='post')
{
if (type=='json')
{
var j = JSON.parse(xhr.responseText);
console.log(j);//Check your browser's developer network panel.
eval(j.javascript);//eval is frowned upon though just use to call a sequel JS function.
}
}
}
}
}
//Example uses:
ajax('get','admin/?ajax=account','inside','id_target');
var fd = new FormData();
fd.append('ajax','admin_post_account_approval');
fd.append('parameter1',object1);
fd.append('parameter2',object2);
ajax('post',path+'admin/',fd);
Your goal is to make your code minimal and highly reusable when possible.
In regards to the server and PHP you need to remember: never trust the user. That means you need to verify everything:
<?php
if (isset($_POST['ajax']) && $_POST['ajax']=='admin_post_account_approval')
{
if (!isset($_POST['parameter1'])) {/*error_handling*/}
else if (!isset($_POST['parameter1'])) {/*error_handling*/}
else if (![condition not met]) {}
else
{
if ([all conditions met])
{
header('Content-Type: application/json');
$array = array('javascript'=>'alert(\'Just a JavaScript alert triggered by PHP.\');');
die(json_encode($array));
}
}
}
?>
Server side code, PHP should be thought of like real life: always fail first and test the conditions for length, proper characters or improper characters in form parameters, etc.
Additionally I highly recommend having the server respond with JSON as I generally illustrated in the code above. Because I only write my own code and don't work with other people's code this is more of a generic response than attempting to target whatever software you're working with. Regardless if you enable error reporting and pay attention to your developer tools in whichever browser you're using you'll get there. Good luck.

How Can I repeatedly get data from a php file till a certain condition is met?

I have a php file that gets a word from a database randomly and json encodes it. I want to get the word using jquery but also make sure that word isn't in a list already. I'm confused on how I can repeatedly hit the server till my condition is met. Here is what I have:
php:
<?php
$sql = "SELECT * FROM words ORDER BY RAND() LIMIT 1";
$result = $db->query($sql);
$row = $result->fetch_assoc();
$word = $row['word'];
echo json_encode($word);
?>
Jquery function:
$(document).ready(function() {
$("#newRound").on("click",function(){
$.getJSON("getWord.php",function(data){
//check here if data is already in wordsSoFar arary and if it is, get another word from getword.php
document.getElementById("input1").style.visibility = 'visible';
currentWord = data; //set the current work
lives = 6; //reset lives
tracker = 0;
incorrectLettersGuessed = "";
allGuessedLetters = "";
updateLetters();
document.getElementById('hangman').innerHTML = '<center><img src="stage1.png"></center>';
createTable(currentWord);
output.innerHTML = '<center>'+messages.validLetter + '</center>';
alert(currentWord);
});
});
});
if you want a sql solution:
$sql = "SELECT * FROM words WHERE column_name NOT IN ('yourword1','yourword2','youword3'...) ORDER BY RAND() LIMIT 1";
EDIT: i saw your comment too late (Check it on client side).
here a jquery solution (because youre working with jQuery):
$.each(yourwordsarray, function( index, value ) {
if(value == word_is_in){
.. do what you want with the word
}
});
Save the words which the database already gave you in another table then just check if the new word is not on that table.
That table could also have an userID to identify the words which the database gave you to that user and a datetime column to check the date when the user play your game, so you could repeat words from past days.
It's better if you validate this on your database :)

Error updating webpage elements in real time with JavaScript

I am working on a webpage that shows the amount of online players on a game server that I am running, that is updated in real time.
The problem is that I can get the amount of players online in the game server to display, but it never updates and always shows the amount of players that were on the server when the page was loaded although people leave and join the server every second.
This is the PHP code that shows the numbers (it's simple, just for testing):
<?php
echo "<a id='a1' href='#' class='online'>Loading...</a>";
?>
What I am doing is to update 'a1' every second with the new amount of online players using javascript, which calls a php function called getplayers():
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = '<?php echo getplayers()?>';
}, 1000);
</script>
The function getplayers() it's exactly this:
<?php
include "Status.php";
function getplayers() {
$serverb = new Status("mc.spainpvp.com", '25565');
return $serverb->online_players;
}
?>
Lastly, Status.php is a script that gets the amount of players online and more things about the server, which I am sure that works:
<html>
<?php
class Status {
public $server;
public $online, $motd, $online_players, $max_players;
public $error = "OK";
function __construct($url, $port = '25565') {
$this->server = array(
"url" => $url,
"port" => $port
);
if ( $sock = #stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {
$this->online = true;
fwrite($sock, "\xfe");
$h = fread($sock, 2048);
$h = str_replace("\x00", '', $h);
$h = substr($h, 2);
$data = explode("\xa7", $h);
unset($h);
fclose($sock);
if (sizeof($data) == 3) {
$this->motd = $data[0];
$this->online_players = (int) $data[1];
$this->max_players = (int) $data[2];
}
else {
$this->error = "Cannot retrieve server info.";
}
}
else {
$this->online = false;
$this->error = "Cannot connect to server.";
}
}
}
?>
</html>
So my question is if someone knows why it always updates with the first number of players instead of putting the new number of players?
You can not call PHP functions by Javascript. PHP is processed on a server in time of request. No piece of PHP code will be visible in response, because it's already processed.
So your javascript code will actually look like:
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = 'XXXXX';
}, 1000);
</script>
where XXXXX is amount of players in the time of request.
So your code will every second replace elements innerHTML with the static content.
If you want to get new amount of players every second, you need to use Ajax.
You can create request on your own using XMLHttpRequest or you may use some library like jQuery and it's $.ajax method.
You also need a PHP code on a server that will provide such information.

PHP validation to check if record exists

I'm trying to create a validation for a form. When a user fills out the form, it is supposed to run a set of queries. The first is to check if a records already exists in the table. If it does exist, then it doesn't need to run the the next 2 queries, which are to INSERT and UPDATE.
I'm not sure what I am doing wrong, but the table already has an existing record. After checking the table, it still runs the INSERT and UPDATE queries. They should not fire. It should not do anything.
Here is my code: * I'm starting my code from the for loop, which is just taking an array of BOL numbers and CONTAINER numbers that the user manually selected. I exploded the array, but I will not show that code as I do not think it is necessary to show in this case *
<?php
for($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$checkService = "SELECT * FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'";
$checkSerRes = mysql_query($checkService);
$checkSerNum = mysql_num_rows($checkSerRes);
if($checkSerNum > 0)
{
$successService = false;
}
elseif($checkSerNum = 0)
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query ("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
// javascript fires an ALERT message in this next set of code
if($successService = true)
{
echo ("<script language='javascript'>
window.alert('Record has been saved')
window.location.href=''
</script>");
}
// if checkSerNum > 0, then it should skip the INSERT and UPDATE and fire the code below
elseif($successService = false)
{
echo ("<script language='javascript'>
window.alert('There was an error saving the record')
window.location.href=''
</script>");
}
?>
I'm not sure why this is not working correctly. I need this validation to work. I'm sure there is an alternative method, but this is what I got.
Please help me make this work.
Thank you in advance.
This elseif($checkSerNum = 0) needs to be elseif($checkSerNum == 0)
You're presently doing an assignment instead of a comparison.
Including if($successService = true) and elseif($successService = false) so add another = sign.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
http://www.php.net/manual/en/function.mysql-error.php
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
This isn't quite efficient (you are selecting * from your table, which you aren't using - waste of memory?). Why don't you do something like this:
for ($i = 0; $i < $count; $i++)
{
$bolService = $bolArray[$i];
$conService = $conArray[$i];
$recordExists = false;
$result = mysql_query("SELECT COUNT(*) AS recordCount FROM import_service WHERE bol = '" . $bolService . "' AND container = '" . $conService . "'");
if ($result) {
$row = mysql_fetch_assoc($result);
$recordExists = ($row['recordCount'] >= 1);
}
if ($recordExists)
{
$successService = false;
}
else
{
$sql_query_string = mysql_query
("INSERT INTO import_service (bol, container) VALUES ('$bolService','$conService')");
$updateService = mysql_query
("UPDATE import_dispatch_details SET SERVICE = 'Y'
WHERE BOL_NUMBER = '$bolService' AND CONTAINER = '$conService')");
$successService = true;
}
}
P.S. mysql_* is officially deprecated. Please use PDO or MySQLi. Also, your code is potentially open to SQL Injection.

Categories