Runs php code from JavaScript in impact engine - php

I have created a game in using impact game engine called Staroids.
I have created a database to store the highscores.
I have done what it says on this previous answer and looked at a few other solutions, but it doesn't seem to work!
I am trying to run a php file which contains the following code:
<?php
$connect = mysql_connect('localhost', 'root', 'password');
mysql_select_db('staroids', $connect);
$sql = 'INSERT INTO staroids (score) VALUES ("'.$_POST['score'].'")';
$result = mysql_query($sql);
?>
Here is the code that I run in the JavaScript file:
$.post('scripts/register.php', {score: score}, function(){}).error(function(){
alert('error... ohh no!');
});
It comes up with the following error in console when it reaches this code:
Uncaught ReferenceError: $ is not defined

You're probably not loading jQuery into your page correctly. Make sure you have the script tag in the head that loads jQuery and troubleshoot to make sure it's actually loading jQuery at all.

I solved it with the help from the comments above and using a lot of trial and error, here is the working code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
//make sure you run this otherwise the $post request wont work!
Then where in the JavaScript function where I wanted to run the code I put:
$.post('register.php', {score: this.score}, function(){}).error(function(){
alert('error... ohh no!');
});
//this runs the php file parsing through the score variable
Here is the PHP code which I then run to add the parsed through variable to the table in the database:
<?php
$score = $_POST['score'];
mysql_connect("localhost", "root", "password");
mysql_select_db("staroids");
mysql_query("INSERT INTO scores (score) VALUES ('$score')");
?>

Related

Send data from bash CGI to PHP

I have a PHP script to receive a html/txt data and store it into a MySQL database. The PHP is like this and is in the following path XXX.XXX.XX.158/myphp.php
<?php
$text = $_POST['data'];
$con = mysqli_connect('localhost','root',''); //DB connection
mysqli_select_db($con,'db1'); //DB selection
$sql = "INSERT INTO pages (page) VALUES ($text)";
mysqli_query($con,$sql);
?>
On the other hand, I need a BASH-CGI in other local IP (XXX.XXX.XX.157) to send the html/txt file. However, curl is not working for me and I dont know how to do this in pure bash.
#!/bin/bash
dir='Location: ../http/index.html'
#POST($dir) send(data)??
Is there any command or method so I can do this?
Thank you in advance

Running concurrent database queries in PHP per session?

I appear to be having some difficulties with handling running multiple database calls, especially in regards to large datasets being returned. It appears that PHP only lets you have one database call running at a time, per session. This normally isn't an issue, as the database calls tend to be so small it doesn't lock anything up, but the large ones cause this waiting issue.
I discovered this issue when I fixed an unrelated issue, and discovered that if you click a button to query the database via an AJAX call, then try to refresh the website, it won't start loading the website until that database call is done, as the page does have an internal function to make a database call. Conversely, if I were to start the database query, then load up a pure html webpage stating "Hello World", it loads instantly. Based on this, Apache isn't having an issue serving, it's something to do with database connections.
To point, I've isolated code that's possibly relevant, as I can't figure out why I'm only able to have one active call at a time. In short, is there a way to have multiple database calls running per user at a time, or will a user have to wait?
db_connect.php:
<?php
$user = 'TEST';
include_once 'config.php'; //Intialize constants for the connection
$conn = oci_connect(USER, PASSWORD, '//'.HOST.':1630/'.DATABASE);
oci_set_client_identifier($conn, $user); //Identify who's making these calls.
?>
events.php: (if I refresh this after clicking the ajax button to do the same fetch, it won't load until that AJAX call is finished. Doesn't matter if I have code to abort the call, the database is still running that database query.)
<?php
session_start();
include 'db_connect.php';
include 'database/event_defs.php';
?>
<html>
<!-- boilerplate nonsense -->
<body>
<table>
<?php
$dataset = get_event_list($conn, $_SESSION['username']); //Returns 1000 records, could take a while to fully retrieve it.
foreach($dataset as $key => $val) {
//Make multiple rows happen here.
}
?>
</table>
<button onclick="do_ajax_call('get_event_list');">Make DB Call</button>
</body>
</html>
database/event_defs.php: (Probably the most relevant part).
<?php
function get_event_list($conn, $user) {
$l_result = array();
$sql = 'BEGIN ...(:c_usr, :c_rslt); END'; //name is irrelevant.
if($stmt = oci_parse($conn, $sql)) {
$l_results = oci_new_cursor($conn);
oci_bind_by_name($stmt,':c_usr',$user);
oci_bind_by_name($stmt,':c_rslt',$lresults,-1,OCI_B_CURSOR);
if(oci_execute($conn)) {
oci_execute($l_results); //Problem line, seems to stall out here for a while and won't let the user query again until this call finishes.
while($r = oci_fetch_array($l_results, OCI_ASSOC) {
$l_result[] = $r;
}
} else {
return 'bad statement';
}
} else {
return 'unable to connect';
}
return $l_result;
}
?>
Version information:
PHP 5.4.45
Oracle 11g
Apache 2.2.15
As MonkeyZeus monkey has already pointed out in the comments to your question, the second request is most likely only blocked by the session mechanism.
Since it looks like you don't need anything but the username from the session, just grab that value and finish the session mechanism.
<?php
session_start();
// check $_SESSION['username'] here if necessary
$username = $_SESSION['username'];
// no need to keep the session mecahnism "alive"
session_abort(); // and since nothing has been written to _SESSION, abort() should do.
require 'db_connect.php';
require 'database/event_defs.php';
?>
<html>
<!-- boilerplate nonsense -->
<body>
<table>
<?php
$dataset = get_event_list($conn, $username); //Returns 1000 records, could take a while to fully retrieve it.
foreach($dataset as $key => $val) {
//Make multiple rows happen here.
}
?>
It's PHP session blocking mechanism.
You need to call session_write_close() when you don't need session any more.
May be after this string:
$dataset = get_event_list($conn, $_SESSION['username']);
After calling session_write_close() you can't use $_SESSION.

Easy Contact Forms plugin does not work with PHP 5.5.9

The WordPress plugin Easy Contact Forms doesn't with WordPress 3.9 and PHP 5.5.9
It doesn't show the form fields, nor you can edit, and it won't show the form in the website.
I notice because it gives me this error:
Ajax error. Status =error Internal Server Error
I look at the log files and see the error is in the file:
easy-contact-forms/easy-contact-forms-database.php at line 152, due to the function mysql_real_escape_string
I tried to use another similar functions, but either doesn't work, or deletes data, or doesn't work for every query.
After watching the file code, you can realize that this plugin is not perfectly made, it's inconsistent. It changes it's MySQL connection !
One quick fix to make it work, (I know this is not the best way):
in the wptn function add:
mysql_connect('localhost', 'user', 'password');
Like this:
function wptn($query) {
global $wpdb;
mysql_connect('localhost', 'myuser', 'mypassword');
$query = str_replace("#wp__", $wpdb->prefix, $query);
return $query;
}

PHP - require_once in multiple pages

I am using LAMP stack to develop a PHP application. I am using require_once to include class files. I need to use the functions in those class files in more than one PHP page. So, I am including those class files in all the required PHP pages using require_once. But, if I include those class files in more than one page, the PHP file goes blank. It displays nothing. View source also displays nothing.
Files: test.php, process.php and class.test.php
test.php has
<?php
session_start();
require_once 'classes/class.test.php';
.
Few more classes
.
.
?>
<html>
<form name = "myForm" method="POST" action="process.php">
<input type = "text" name="username" value=""/>
<input type = "submit" value="Submit" />
</form>
</html>
process.php
<?php
session_start();
require_once 'classes/class.test.php';
$obj_test = new test();
$obj_test->test();
?>
class.test.php
<?php
session_start();
require_once 'class.misc.php';
require_once 'config.php'; //DB connection details
function test()
{
$obj_misc = new misc();
$id = $obj_misc->random_ID();
$username = $_POST['username'];
$query = "INSERT INTO test_table VALUES ('$id','$username',NOW());
mysql_query($query);
}
?>
Now, it returns a blank page. If I comment out the require_once in process.php, the test.php page displays the form, but on submitting the form the process.php throws an error "class test not found".
I am struggling with this problem for the past 2 weeks. :( It was working fine before that. I don't understand what went wrong. Please help.
You have an error in the PHP code for process.php; you are missing a semicolon:
require_once 'classes/class.test.php'
should be:
require_once 'classes/class.test.php';
If that doesn't fix it, then there is probably some other error somewhere in your code. Without access to the full source, we won't be able to do much.
For future reference, if a page goes blank, there is usually a problem with the PHP source code (ie, some type of interpreting error). As part of good debugging tactics, look into display_errors and error_reporting
Try out with
error_reporting(E_ALL);
Sounds like your error reporting is turned off. You should check your error logs to see what exception is being thrown when it's failing silently (that will give you a little more insight).
Additionally, you may want to add this at the top of your process script:
error_reporting(E_ALL);
Require once is a function ...
try adding the parens ...
require_once( 'classes/class.test.php' );
looks like you are missing a closing qoute on the sql query
$query = "INSERT INTO test_table VALUES ('$id','$username',NOW());
mysql_query($query);
should be
$query = "INSERT INTO test_table VALUES ('$id','$username',NOW())";
mysql_query($query);

Updating MySQL using SESSION variables via a jquery javascript function

I currently have a javascript file 'score.js' which makes use of jQuery.js, which is being called correctly via a link. The code in score.js is:
function originalUpdateScore(answer,correct){
if (answer == correct)
{
$.post('updateScore.php');
}
window.location.reload(true);
}
This function calls 'updateScore.php':
<?php
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
mysqli_query($con, $updateScore);
?>
However the database is not being updated correctly. If I replace the line:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
with:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='123pf')";
Where 123pf is the value that the SESSION variable contains in the php file calling the javascript it updates correctly. Why does using the session variable not work? Am I calling it incorrectly in the query?
Thanks in advance.
Are you calling session_start anywhere inside updateScore.php?
If you haven't started the session I do not believe that session variables will be available.
also, do you have complete control over $_SESSION['logname']? If not, someone could easily change their logname to inject SQL and damage/compromise your database. For example, if they were able to set their logname to be this, you could lose your user table:
$_SESSION['logname']="'; DROP TABLE user;-- ";
You're opening yourself right up to cheaters by playing like this. Under this scenario, any user could visit updateScore.php at any time to increase their stats, since that script neither checks their answer nor checks for a token that the JS builds to say the score is ok. It is a bad idea to keep this kind of logic on the front-end (javascript) without also having it verified on the back end (PHP); javascript & AJAX are very helpful shortcuts that can improve user experience, but they cannot be trusted as sole validity checkers.
It's probably just a transcription error, but the code that you have shown in your question uses $_SESSION[logname], it should be $_SESSION['logname'].

Categories