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...
Related
Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}
i think im missing some post variables in this code. I'm not exactly sure how to place the post variables and link them to the controller in order to get submission forms going. I've read hours and hours and my minds still fuzzy on the concept. Now with this php controller, i can manually enter in data, but automatically uploading it via form is confusing me. I think im making it overly complicated and i know its just 1 or 2 steps from being completed. My mysql server is behind my lan, so the only thing that is publically accessable is my port 80 website. I hope i can get this resolved, its been murder on my brain lately lol
If i can't figure it out, ill just migrate it over to web2py. its more confusing but easier on the database front from what i've seen in organization of syntax. One last problem. The database isn't automatically creating new ID rows. I have it set to primary in the database and should automatically create new records, but for some reason it doesn't.
<form action="SubmissionForm.php" method="post">
<label>Name:</label><input type='text' name='user'/>
<label>Message:</label><input type='text' name='message'>
<input type='submit' value='Submit'>
</form>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO testmessage2 ". "(user, message) ". "VALUES(user, message);
mysql_select_db('politicalagenda');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
//captured the form data in variable
$user= mysql_real_escape_string($_POST['user']);
$message= mysql_real_escape_string($_POST['message']);
$sql = "INSERT INTO testmessage2 (user, message) VALUES('$user','$message')";
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.
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.
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.