how to insert javascript variable into mysql database? - php

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.

Related

Track Links Clicked On My Website Using HTML and PHP

I have a website that I would like to record on links clicked on each page. As an example, below is the code for my index.html page in which I attempt to record a link:
ADA
Where "trackIndexPageLinks.php" is the name of my php file and "?token=1" is the php variable and value that I would like to record in my server.
Listed below is the php code that I use to store the value and pass it to my server:
<?php
$db_hostname = '???.?.?.?';
$db_database = 'mySiteDB';
$db_username = 'something';
$db_password = '';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die("Unable to connect to MySQL:".mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: ".mysql_error());
echo #mysql_ping() ? 'true':'false';
$token = $_GET['token'];
//Create insert statement - inserts data into the database.
$sql = "INSERT INTO clickLog (linkClicked)
VALUES ('$token')";
//Error check to ensure SQL statement took.
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
//Close connection.
mysql_close();
?>
However, I get no recorded records. Any assistance on this would be greatly appreciated.
You're much better off to sign up with google analytics and add snippets of javascript code they provide. They can give you complete detail as to who is linking to what on your page as well as what links they click as well as the order they click them in.
Go to: http://www.google.com/analytics/
All you need is a google account and if you don't have one, you can sign up for one. The whole thing is free.

How can I get a specific data using SQL select query?

I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>

posting a variable from javascript button to php with mysql

I'm quite new to PHP and Javascript. I am trying to get a variable from a google maps API marker with an option to delete the marker and its information from a MySQL database. No errors are being generated, however the row is not being deleted. I suppose that the problem is with the POST. Below is the code I have related to this matter:
var html = "<b>" + name + "</b> <br/>" + location + "<br/> <br/> <input type='button' value='Get Directions from your Current Position' onclick=getDirections()/> <br> <input type='button' name = 'remove' value='Remove Pointer' onclick=removePointer("+name+")/>";
That is the line where I am calling the removePointer function, passing 'name' as a parameter
function removePointer(name){
var nameSend = name;
$.post("index.php", {variableName: nameSend});
<?php
$mysql_host = "xxxx";
$mysql_database = "xxxx";
$mysql_user = "xxxx";
$mysql_password = "xxxx";
$link = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database) or die(mysql_error());
$removeName = $_POST['variableName'];
mysql_query(("DELETE FROM markers WHERE Name='" . $removeName . "'"),$link) or die ("Markers Table Error: " . mysql_error());
?>
}
That is the removePointer function, where it should get the javascript variable, post it, and a PHP block to get the post and remove the MySQL row accordingly.
Thanks in advance for any help!
In your case, Javascript is something that will run in the user's browser while PHP is something that will run on the server (which will need to be able to talk to the database server). That is, you cannot embed PHP inside of a Javascript function and expect the PHP to be run - web browsers do not execute PHP. Further, you NEVER want to put any sensitive information into Javascript that will be running in a browser (such as MySQL credentials), because it will be visible to anyone who loads that Javascript.
You will need to create a server-side PHP script that Javascript will communicate with. Javascript could make an AJAX request to the PHP script, POSTing the data you wish the PHP to take action on. In this case, the removePointer() function could post the marker name to the PHP script, which would then remove it from the database.
To make life easier, you might consider using a Javascript library such as jQuery, which can greatly simplify making Ajax requests.
you cannot post just to your index.php page. create a new one "del.php", put your php code there, and post to that page:
index.php
function removePointer(name){
var nameSend = name;
$.post("del.php", {variableName: nameSend});
}
del.php
<?php
$mysql_host = "xxxx";
$mysql_database = "xxxx";
$mysql_user = "xxxx";
$mysql_password = "xxxx";
$link = mysql_connect($mysql_host, $mysql_user, $mysql_password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysql_database) or die(mysql_error());
$removeName = $_POST['variableName'];
mysql_query(("DELETE FROM markers WHERE Name='" . $removeName . "'"),$link) or die ("Markers Table Error: " . mysql_error());
?>
of course im no php-expert, and that is for sure not the optimal way to do ajax requests, but i hope you understand the concept of ajax a little bit better know...

How to show image using php?

I am just starting to use html, php, and mysql. I've successfully logged into my database using php, and formed a query. I now want to go a step further and show a picture instead of just strings or numbers.
The variable 'result' will be returning a string that has a url to an image i want to display on this webpage. How would I do this?
<html>
<head>
<title>My First Question</title>
</head>
<body>
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
echo 'Successfully connected to database!';
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
?>
</body>
</html>
Inside PHP, This will turn your SQL response into a usable variable.
$result = mysql_fetch_assoc(mysql_query($query));
Outside of your PHP tags, Echo the URL from the table into the SRC of an IMG element.
<img src="<?= $result['url_column_name'] ?>"/>
This will create a new IMG element with the source being the URL that you have fetched from your SQL query.
Short tags are also a way of echoing PHP variables in HTML.
<?= $var1, $var2 ?>
is the equivalent of using
<?php echo $var; echo $var2; ?>
This is a simple case of echoing the relevant HTML. You'll also have to fetch the results after you execute the query -
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo '<img src="'.$data['image'].'" />;
For added security, a good practice would be to escape any possible unwanted HTML content in your images path - htmlspecialchars($data['image']).
It should also be noted here that you are using a very old deprecated method to access your database. You might want to think about updating your code to use more modern PDO methods.
So what? simply use it as a source to your image
<?php $imgname = mysqli_fetch_array($connection, $result); ?>
<img src="<?php echo $imgname['image_column_name']; ?>" />
And btw use mysqli_() or PDO instead of using mysql_() as community is not maintaining it anymore
Once you update your mysql to mysqli you can echo the image's url in an html img tag as so:
echo '<img src="'.$result['image'].'"/>';
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
header("Location: $result");
?>
should work

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Categories