简体   繁体   中英

how to insert javascript variable into mysql database?

I cant seem to work out how to simply add a javascript variable into a mySQL table!

I have a html code which is just making a canvas for my game. I then have a javascript file doing all the game proccess and here is the code i am using to send the javascript variable to a php file:

 var uiStats = $("#gameStats");
var uiHealth = $(".gameHealth");

var health = 10;

$.post('http:/localhost/basic_structure/game.php', { "health" : health});

Then here is the php file to insert the data into the database:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';

$conn = mysql_connect($dbhost, $dbuser, $dbpass)
    or die
('Error connecting to mysql');

$dbname = 'game';
mysql_select_db($dbname, $conn);

$health = $_POST['health'];

mysql_query("INSERT INTO game_table (health)
VALUES ('$health')");

mysql_close($con);

I simply just want to save the health of the player in my game for later uses.

Any help is appreciated

Thanks

If you copy/pasted this from your actual code,

'http:/localhost/basic_structure/game.php'

should be

'http://localhost/basic_structure/game.php'

Your URL is incorrect in the post call

Also, use PDO or mysqli_ instead of mysql_ because mysql_ is deprecated.

A third suggestion is you should have a callback in your post (from php to javascript) to allow you to check that the process succeeded/failed and inform the user accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM