Make sure most recent SQL query result is used in autosuggest - php

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

Related

php long polling using mysql

I found a script that uses php long polling.
It uses the following code to see if the text file is changed and returns the content.
This is received by the browser.
How can i change this to read a table and see if there are new events ?
$filename= dirname(__FILE__)."/data.txt";
$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}
$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);
I have a table where there are 'posts'. post_id,content,user_id,posted_time
How can i know if theres a new post ?
You basically just have to fetch a new result, thats it, if you want to check if there are new results since the last execution of the script you have to save the output somewhere (is that what you want to do?)
See the following code, for a regular MySQL query:
<?php
// Connect to your MySQL DB
#$db = mysqli_connect("localhost", "root", "", "database");
// Check connection and echo if an error occurs
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
// Execute SQL Query, replace this with your Query (maybe the one I put in fits for your needs)
$query = mysqli_query($db, "SELECT * FROM posts");
// Transform the result into an array if your you got new elements in the MySQL DB.
$resultat = mysqli_fetch_assoc($befehl);
// Close connection
mysqli_close($db);
?>

Dynamically update variables in external PHP XML generation script

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

Waiting for task in PHP to finish before moving to next item

Quick question here, i've got a process running that grabs RSS feeds and adds them to a mySQL database.
During this process I'll be using the Readability API to grab the URL content as I go.
Now this works fine on single entries, but as this script can have hundreds of entries, nothing is being inserting into my database.
I'm wondering if it's not getting a chance to finish the process and immediately skipping onto the next entry in the RSS.
Can anyone suggest a way of letting it finish before moving on? Code below:
$db_hostname="localhost";
$db_username="myusername";
$db_password="mypassword";
try
{
/* query the database */
$db = mysql_connect($db_hostname,$db_username,$db_password);
if (!$db)
{
die("Could not connect: " . mysql_error());
}
mysql_select_db("MyDB", $db);
// Get stories that don't have a the readability assigned
$query="select item_id, item_url from tw_articles_parse where story_readability = '' LIMIT 0 , 1";
$result=mysql_query($query);
$num=mysql_numrows($result);
// Close the DB connection
mysql_close();
// Start the loop of source RSS feeds
$i=0;
while ($i < $num) {
$item_url=mysql_result($result,$i,"item_url");
$item_id=mysql_result($result,$i,"item_id");
// Parse the story URL into the Readability API
$url = "https://www.readability.com/api/content/v1/parser?url=$item_url&token=myapikey";
// Get the contents of the JSON returned by the API
$json = file_get_contents($url);
// Decode the JSON
$out = json_decode($json, true);
// Set the content as a variable
$story = mysql_real_escape_string($out['content']);
// Insert into the DB - Adding 0 to story_club_id as default
$item_insert_sql = "UPDATE tw_articles_parse SET story_readability=$story WHERE item_id='" . $item_id . "'";
$insert_item = mysql_query($item_insert_sql, $db);
$i++;
}// end the loop of feeds
} catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Probably nothing is inserted because you are using UPDATE statement and there are simply no such records with correspoding item_id to be updated?
Try changing UPDATE query to INSERT ... ON DUPLICATE KEY UPDATE
Unfortunately we don't know your database scheme, but something like this should work:
$item_insert_sql = "INSERT INTO tw_articles_parse (story_readability, item_id) VALUES ('$story', $item_id) ON DUPLICATE KEY UPDATE story_readability='$story'";
Maybe you're running out of memory or time? Enable warnings and error reporting:
ini_set("display_errors", 1);
error_reporting(E_ALL);

generating XML from mysql server for iphone app consumption not working

I am trying to generate some xml with this php code here... I am trying to use this script for an ios app I am learning from as I go just to figure out how each of the parts fit i.e. (app, php, mysql, xml)
Here is my php script that my ios app is exicuting
<?php
header("Content-type: text/xml");
$username="*****";
$password="***";
$database=" *****";
$testcode=$_REQUEST['usercode']; ////testcode coming from ios app
//connect to database
$connect = mysql_connect('localhost',$username,$password) or die('No DB Connection');
//select database
$db = mysql_select_db('N_codes', $connect) or die("<b>Unable to select specified database</b>");
//Do some stuff here
$query = "SELECT codes FROM codes where id = '$testcode'"; //testcode coming from ios app
$result = mysql_query($query,$connect);
//XML STUFF
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";
$row = mysql_fetch_assoc($result);
$xml_output .= "\t\t<code>" . $row['codes'] . "</code>\n";
$xml_output .= "</entries>";
echo $xml_output;
?>
This is all that it is producing
<?xml version="1.0"?>
<entries>
<code></code>
</entries>
What I am looking for is a code that should be between that is in the mysql database and is found by the user supplying a code that is passed to the php script.
Can anyone see whats missing?
I see a few "potential" problems with the code you provided above.
1. Is your table named codes and the field you're looking for also codes? Your SQL question is looking for a field name codes in a table called codes. It's hard to tell whether or not that's a problem but must rows represent a single field so the plural version of the word "code" makes me believe you made a mistake there.
$query = "SELECT code FROM codes where id = '$testcode'";
2. Try adding a die after the query that outputs [mysql_error][2] just in case an error occurred.
$result = mysql_query($query, $connect) or die(mysql_error($connect));
3. You should use mysql_real_escape_string when you use user supplied data in a SQL query.
$testcode = mysql_real_escape_string($_REQUEST['usercode'], $connect);

MySQL and PHP display problem?

I can't get the following code to display items from the database where the parent_id is equal to the id.
Here is the code below.
// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories WHERE id=parent_id");
if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error();
}
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<li>' , $row['category_name'] , '';
}
I think I know what I'm doing wrong how can I have this query check a previous query?
I'd put the SQL query in a var so you can output it, then try this direct in the database to see if there are any matching rows:
$mysqli = new mysqli("localhost", "root", "", "sitename");
$query = "SELECT * FROM categories WHERE id=parent_id";
echo $query;
i think this line should be rethought:
if ($row['parent_id'] == $row['id']) {
cause are u sure its the correct logic?
Try do do something like:
if ($row['parent_id'] == $row['id']) {
echo '<li>' , $row['category_name'] , '';
}
else {
echo "there is no match!";
}
And see if the problem is, in fact, not in the SQL query but in you app logic (which I think is more likelly).
That said try to debug SQL queries with phpMyAdmin. Just post the query you want there and check for the output. If the output is ok, look into your logic, if not look into your query.
Do try to split your problem into smaller chunks, makes your debugging much easier.
Hope it helps.

Categories