Dynamically update variables in external PHP XML generation script - php

I have a simple php script, very similar to that demonstrated in the google developers examples, which creates XML data from the results of a MySQL query. I'm then using this XML to drive a map displaying waypoints for a given itinerary.
The problem that I have at present is that whilst the page showing the waypoints works, I don't know how to dynamically update the script below with the said itinerary ID. I would normally use $_GET to pass a variable, especially with a non-sensitive ID, but as this script is a separate file to the page displaying the mapping output, I'm not sure how to dynamically update variables within it.
If someone can explain how I can pass a value to this script so as to update the itineraryID within the query that I have marked as '!!!!' it would be much appreciated.
<?php
require("phpsqlajax_dbinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",'&apos;',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a mySQL server
$connection=mysql_connect ($db_host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the locations table
$query = "SELECT itinerary_link.itineraryID, itinerary_link.coursesID, itinerary_courses.coursename, courses.lat, courses.lng FROM itinerary_link LEFT JOIN itinerary_courses ON itinerary_link.coursesID = itinerary_courses.coursesID
LEFT JOIN courses ON courses.coursename = itinerary_courses.coursename WHERE itineraryID=!!!! ORDER BY coursename";
$result = mysql_query($query);
//$ti1 = "U8abKhsdiu";
//$hashed = $row['coursename'];
//$bh= sha1($hashed);
//$tileimage = sha1("$bh$ti1");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// Define variables for infoWindow images
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['coursename']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>

I can't comment on posts yet, or I'd just ask for clarification. But I have to make assumptions about how you are using this script:
If you accessing this script through an include in the page that uses it then you can use $_GET and $_POST in the way that you are familiar.
But I suspect that's not the way you're doing it as you said dynamically!
Which means calling the script from the page you want to update using AJAX (asynchronous javascript and xml) or jQuery's simpler ajax functions.
The idea is you call this script with jQuery or AJAX from the page you want updated and then use the results (your XML) to update the page.
These methods allow post GET and POST information to be sent as well. The examples below show their usage, but you'll have to follow the links to see the proper, full, implementation.
Whichever method you choose, at the PHP end you use the same $_GET/$_POST with which you are familiar.
AJAX: ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
full example: http://www.tizag.com/ajaxTutorial/ajax-javascript.php
jQuery: $.get("test.php", { name:"Donald", town:"Ducktown" });
full example: http://www.w3schools.com/jquery/ajax_get.asp

Related

How do I access the index of mysql_fetch_array from database in php?

I know how to fetch data using mysql_fetch_array and one variable will hold the data, but after fetching the data I want to access and print my desired index from the fetched data.
My current code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("htmlcontent", $con);
$s = mysql_query("SELECT * FROM tags WHERE place = 'luzon'");
while($roww = mysql_fetch_assoc($s))
{
$pt2 = $roww['url'];
echo "$pt2" ."<br>";
}
?>
Your code would print the value held by the url field in your tags table.
You do not have to put $pt2 within quotes, just use echo $pt2 . "<br>";
Also, I would recommend you use PDO or mysqli to make it work.
You may use mysql_fetch_array instead, (if you need array indexes too).
PS. I highly recommend you use PDO or mysqli instead of mysql.

Hiding a PHP JSON output from showing in view source

I would like to hide my JSON php output in view source, I am working with amCharts and have created PHP data sources that pull the data from a mySQL database and format it to JSON format so that amcharts can read it. Is it possible to hide the formatted JSON data in view source and still have amcharts read it.
My PHP code below. Your help is greatly appreciated.
<?php
// Connect to MySQL
$link = mysql_connect( 'localhost', 'root', 'VPM2014' )
or die( 'Could not connect: ' . mysql_error() );
// Select the data base
$db = mysql_select_db( 'vpm_global', $link ) or die ( 'Error selecting database \'vpm_global\' : ' . mysql_error() );
// Fetch the data
$query = "SELECT Price_date, ZAR_Based_1000 FROM gso ORDER BY Price_date ASC";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_array( $result ) ) {
echo $prefix . " {\n";
echo ' "date": "' . $row['Price_date'] . '",' . "\n";
echo ' "value": ' . $row['ZAR_Based_1000'] . '' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
// Close the connection
mysql_close($link);
?>
There is no way to hide the source and provide your charts with JSON data. If you don't output the JSON, your charts won't have any data.
The only way to hide the JSON data and provide the chart would be to create the chart server-side as, say an image, and use HTML to display that image to the user.
Because the chart library you are using is client side javascript, the JSON must also be available to the client and thus visible to the browser using 'View Source' or other DOM debug tools.
You can't really send data to client and expect you still have a control over what he does with it. You can only make it a tiny bit harder to steal the data. Like by checking HTTP Refere header. Or by scaring the client with a warning about legal stuff and going to court etc. But still, none of these will stop more then 20% of internet population from eventual successful thief.
The only true solution would be, like others said, to not send him these data. Like, to generate the chart on the server (somehow) and send to the client only result as a picture. That way he won't get the raw data, just the graph visualization (at least until he hacks your server).

I'm going to be auto aupdating info from mysql. How do i get the past info to keep displaying along with the new info submitted into the database?

I've figured out how to display info submitted into mysql, but I haven't figured out how to keep the past info there. It's going to show the current post on top and keep adding on top everytime new info is submitted but only display like 10 posts at a time. I hope I am explaining this well.
How to go about doing this, I am completely lost. I've connected to the database and everything and now im to:
echo $hit, $amount, $category;
and stuck. that is displaying the info submitted, but when i submit new info, that info changes and the past info is gone. My question is, how would i get the past info to stay and get the new info to build on top of past info?
Thanks.
Edit: here's more of the code. also, ive been told about mysqli. i just havent changed it yet.
if(!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('can not use' . DB_NAME . ': ' . mysql_error());
}
$hit = $_POST['hit'];
$amount = $_POST['amount'];
$category = $_POST['category'];
$sql = "INSERT into hit (hit, amount, category) VALUES ('$hit', '$amount', '$category')";
$result = mysql_query($sql);
if(!mysql_query($sql)){
die('Error: ' . mysql_Error());
}
echo $hit, $amount, $category;
mysql_close();
?>
After the insert sql you need to do a select query to retrieve all the rows from the database as you are only echoing the currently set values.
You need to also be mindful of sql injection as the values you're adding to the database are not sanitised in any way. Use a command such as mysql_real_esape_string or htmlentities for this.
Before the line echoing the results...
echo $hit, $amount, $category;
You need to have a select query combined with a while loop and the mysql_fetch_array or mysql_fetch_assoc commands to output the rows from the database. A first check is to see if the records are being added to the table.
At no point in your code are you fetching data from the database. You're simply submitting the data from the form to mysql, and displaying it at the same time.
You can fetch data from mysql by doing something like this:
$data = mysql_query("SELECT hit, amount, category FROM hit");
// Adding MYSQL_ASSOC as a second argument tells mysql_fetch_array that
// we want an associative array (we can refer to fields by their name, not just by number)
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
echo '<p>'
.'Hit: ' . $row['hit']
.', Amount: ' . $row['amount']
.', Category: ' . $row['category']
.'</p>';
}
Keep in mind this is all a simplified version of things, and it needs more work, especially on security. I should probably be using htmlentities() here, depending on the data. And you should definitely be protecting against SQL injection if that data is coming directly from a user.

How can i get data from mysql table

I have a couple of easy problems.
First I am trying to get names from database where surname='lion'. I wrote php a file but it didn't work:
$con = mysql_connect("localhost","yata_ali","password");
if (!$con){
die('error: ' . mysql_error());
}
mysql_select_db("yatanada_iBess", $con);
$degisken = mysql_query("select name from people where surname LIKE '%lion%'");
if(mysql_query){
return "$degisken";
}
mysql_close($con);
?>
I wrote this code and tried to use $degisken in my xcode project. But it didn't work.
shortly i am trying to use the names whichs surname =lion in my ios project and i know i should use url.but i couldn find the code part that return name what shall i write at the end of php code ? return or something else to use in xcode.
how can i send response in php? i wonder that. what shall i write "return $name" or something else. i know call url. but i dont know whats the full php code that i shall use
You can't use PHP in an iOS project. You'll need to write some objective-c to call a URL on a server which returns this data in some sort of format (xml? json?) and then have the iOS app parse the response.
I don't think you understand how to use the mysql_* functions in PHP. Take a look at the examples on this page for guidance: http://www.php.net/manual/en/function.mysql-query.php
$degisken= mysql_query("select name from people where surname='lion'");
if ($degisken){
while($row = mysql_fetch_assoc($degisken))
{
echo $row["name"] . "<br/>";
}
}
There are a lot of errors, in your code, but the most serious are that
(a) you are running an invalid test:
if (mysql_query){ //YOU CANNOT DO THIS
(b) You cannot return "$degisken"; because $degisken is a MySQL
resource, not a string.
(c) You should not close your mysql
connection after returning something. You don't necessarily need to
close it at all, but if you're going to, close it after the query
because anything after the return won't be evaluated (assuming the
return is triggered).
(d) If you're looking for cases where the surname='lion' then don't use wildcards in the MySQL query. where surname LIKE '%lion%' will match 'scalion','lioness','slioner', etc.
Your code should look something like this:
$con = mysql_connect("localhost","yatanada_ali","sifre");
if (!$con) {
die('error: ' . mysql_error());
}
mysql_select_db("yatanada_iBess", $con);
$degisken = mysql_query("select name from people where surname LIKE '%lion%'") or die('Error: '. mysql_error());
if (mysql_num_rows($degisken)){
//your query could return lots of results, so you may want to loop through results:
while($row = mysql_fetch_array($query)){
$name = $row['name'];
//do something with the name... I'm going to echo it.
echo $name . "<br />";
}
}

Make sure most recent SQL query result is used in autosuggest

I'm using the PHP code below to get results to return to an autosuggest / autocomplete. The problem is that if an earlier SQL query takes longer to return from the database than the most recent SQL query then the results of the older query will be displayed in the autosuggest results box. So if you start searching for Thomas, it might show the results for Tho if that SQL query takes longer. I was wondering if there is a way to cancel previous queries once a new one is implemented, or to make sure that the most recent query is used?
<?php
// begin XML output
$xmlStr = <<<XML
<?xml version='1.0' standalone='yes'?>
<authors>
XML;
// open database connection
$mysqli = new mysqli("localhost", "user", "pass", "library");
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
// retrieve author list matching input
// add to XML document
$q = $mysqli->real_escape_string($_GET['query']);
$sql = "SELECT AuthorName FROM author WHERE AuthorName LIKE '" . $q . "%' ORDER by AuthorName";
if ($result = $mysqli->query($sql)) {
while ($row = $result->fetch_row()) {
$xmlStr .= '<author name="' . $row[0] . '"></author>';
}
$result->close();
}
// clean up
// output XML document
$mysqli->close();
$xmlStr .= '</authors>';
header("Content-Type: text/xml");
echo $xmlStr;
?>
You might want to synchronize the AJAX calls. Like having a few seconds delay after the key up event and then make the AJAX call. Setting asynchronous = true can also help.
you can abort the ajax call by calling the abort method: XmlHttpRequest.abort() before making the new request

Categories