error: column "undefined" does not exist postgres to_tsquery - javascript

Hi im getting a unidentifiable error from postgres. Would anyone be able to lead me towards to right solution?
'SELECT * FROM photo'+
' JOIN collection ON (photo.collection_id = collection.id)'+
' JOIN photographer ON (photo.photographer_id = photographer.id)'+
` WHERE collection.title = ${category} AND to_tsvector(photo.decription||' '||photographer.name ||' '||photographer.location||' '||photographer.bio||' '||photographer.name||' '|| photographer.twitter_username||' '||photographer.instagram_username) ## to_tsquery(${text})`,
the error reads
error: column "undefined" does not exist

I am assuming that the select you try to run is from node.js.
In that case,
check if variables 'category' and 'text' are initialized with real value,
it seems to me that one of them is 'undefined'
watch out for condition collection.title = ${category} - category is probable string, in that case, quotes are missing, so it should be:
collection.title = '${category}'
the same problem may appear with 'text' too, to_tsquery(${text})
changes to to_tsquery('${text}')

I believe in your JS code you have a problematic variable value. So the variable returns undefined which is directly and unescaped put into the query. The query interprets the text undefined as column name which is, naturally, not existing.
My guess: Check the category and text variables in your JS code.

whoever from the future if you have to deal with this
'SELECT * FROM photo'+
' JOIN collection ON (photo.collection_id = collection.id)'+
' JOIN photographer ON (photo.photographer_id = photographer.id)'+
` WHERE collection.title = ${category}`+
` AND to_tsvector(CONCAT(photo.description, '' ,photographer.name, '' ,photographer.location, '' ,photographer.bio, '' ,photographer.name, '' ,photographer.twitter_username, '' ,photographer.instagram_username)) ## to_tsquery(${req.body.searchBody})`
Thanks for the help guys

Related

Javascript SQLite for Cordova app - search using parameters where a string contains a substring case-insenstive

In my Cordova app, I need to query a SQLite database and select rows where the value of the column EventName contains a substring. I want to be able to use ? to hold values to avoid SQL injection. I tried this query:
SELECT * FROM EventName WHERE 1 = 1 AND lower(EventName) LIKE lower('%?%');
This is my JavaScript code that I use to query the database:
function searchEvent(onSearch, eventName) {
// First create the query string
var params = [];
var query = "SELECT * FROM Event WHERE 1 = 1";
if (eventName != null && eventName != "") {
query += " AND lower(EventName) LIKE lower('%?%')";
params.push(eventName);
}
query += ";";
console.log(query); // Log the query
console.log(params); // Log the parameters
// Then execute query statement
db.transaction(function(tx) {
tx.executeSql(query, params, function(tx, rs) {
onSearch(rs);
});
}, function(err) {
console.log(err); // This statement was executed
});
}
This is the logged query:
SELECT * FROM Event WHERE 1 = 1 AND lower(EventName) LIKE
lower('%?%');
This is the logged paramaters:
[ 'myInput' ]
This is the error the was returned:
{
code: 5,
messsage: 'number of \'?\'s in statement string does not match argument count'
}
As you can see there is 1 ? placeholder and 1 input parameter so the numbers DO match. I think it is because the ? is between the single quotes ('') so it is thought to be a part of the searched string. How do I fix this?
EDIT:
The JavaScript statement "SELECT * FROM Event WHERE 1 = 1" + " AND lower(EventName) LIKE lower('%" + eventName + "%')" is ok, but I wanna use a method that can protect me against SQL injection
In order to prevent the eventName from SQL injection, check it with regEx validation to include only alphanumneric and whitelist specific special characters /^[ A-Za-z0-9_#./#&+-]*$/. Also try this regEx /^[a-zA-Z0-9!##\$%\^\&*)(+=._-]+$/g. I do not believe that ? would work with SQL SELECT statement, so you need to pass +eventname+
Hope it helps.

Display thumbnailPhoto from Active Directory using Javascript only - Base64 encoding issue

Here's what I'm trying to do:
From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes.
Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit).
I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great.
But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues...
I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow:
<img src="data:image/jpeg;base64," />
including base64 encoded byte array at the end of the src attribute.
But I cannot manage to encode it at all.
I tried to use the following library for base64 encoding:
https://github.com/beatgammit/base64-js
But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync.
Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled.
Tried a typeof to find out what the variable type is but it's returning "undefined".
I'm adding here the code I use:
var ADConnection = new ActiveXObject( "ADODB.connection" );
var ADCommand = new ActiveXObject( "ADODB.Command" );
ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" );
ADCommand.ActiveConnection = ADConnection;
var ou = "DC=XX,DC=XXXX,DC=XXX";
var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'";
var orderby = "samaccountname ASC";
var fields = "displayName,thumbnailPhoto";
var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC";
var path = queryType + "://" + ou;
ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby;
var recordSet = ADCommand.Execute;
fields = fields.split( "," );
var data = [];
while(!recordSet.EOF)
{
var rowResult = { "length" : fields.length };
var i = fields.length;
while(i--)
{
var fieldName = fields[i];
if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null)
{
rowResult[fieldName] = true;
}
else
{
rowResult[fieldName] = recordSet.Fields(fieldName).value;
}
}
data.push(rowResult);
recordSet.MoveNext;
}
recordSet.Close();
console.log(rowResult["displayName"]);
console.log(rowResult["thumbnailPhoto"]);
(I replaced db information by Xs)
(There's only one entry returned that's why I'm using the rowResult in the console instead of data)
And here's what the console returns:
LOG: Lastname, Firstname
LOG: 񏳿က䙊䙉Āā怀怀
(same here Lastname & Firstname returned are the correct value expected)
This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/
Summary:
I need to find a solution in Javascript only
I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why
I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly
If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/
Thanks!

If label contains this and not this prepend *

I am trying to add a * if the label contains city, state, and zip. Also I only want it to happen if a * does not exist in the label already. Not sure if you can concatenate contains and not contains together. Also - I cannot edit the forms and some fields have * randomly put in. Here are two ways that failed for me.
Here is the Fiddle-https://jsfiddle.net/4o24kyLw/2/
Here is the jQuery
//$("label:contains('City'):not(:contains('*'),label:contains('Address'),label:contains('State'),label:contains('Zip')").prepend( "* " );
$("label:contains('City'):not(:contains('*'),label:contains('Address'),label:contains('State'),label:contains('Zip')").prepend( "* " );
Got the answer... but maybe I can take this in a different direction... can you simplify the contains. Similar to label:contains('City', 'State', 'etc...'):not(:contains('*')).prepend( "* " ) or maybe a way that works :]
This is the way it will be if it cannot be simplified - $("label:contains('City'):not(:contains('*')),label:contains('Mailing Address'):not(:contains('*')),label:contains('State'),label:contains('Postal Code'):not(:contains('*'))").prepend( "* " );
Rather than setting up a complicated query, you could check for the text within the prepend function itself:
$('label:not(:contains("*"))').prepend(function(_, txt) {
return 'AddressCityStateZip'.indexOf(txt)>-1 ? '* ' : '';
});
Fiddle
The indexOf function looks for text within a string, and it returns -1 if not found.
So if txt was 'City', 'AddressCityStateZip'.indexOf(txt) would return 7.
The conditional (ternary) operator returns an asterisk if there's a match – otherwise, it returns nothing.
Seems to work, you're just missing a )
$("label:contains('City'):not(:contains('*')),label:contains('Address'),label:contains('State'),label:contains('Zip')").prepend( "* " );
https://jsfiddle.net/5686hmnn/
The contains selector is pretty slow, and adding a whole set of them isn't going to help with speed or maintainability. You should use .filter() instead:
$("label").filter(function(idx){
var $(this).text() || '';
return (
(f.indexOf('City') > -1) ||
(f.indexOf('Address') > -1) ||
(f.indexOf('State') > -1) ||
(f.indexOf('Zip') > -1)
) &&
(f.indexOf('*') !== 0);
}).addClass('required');
Also, have you thought about using a css for the call-out instead? It offers several advantages. One of which being you don't really have to worry about modifying the text.
label.required:before { content: '* ' }
Also, you can style this right from the markup and not need to get javascript involved:
<label class="required">..</label>
But if you do need to use javascript it is much easier to find these labels:
$("label.required")

data returned from php function not being detected by if function

I have the following function which acts on an AJAX query:
var formData = $(this).serialize(); //put the form names and values into an array called formdata
$.get('filtertest.php',formData,processData); //jquery ajax call
function processData(data){
if(data =="a"){
$('#content').html("<h2>You have not selected any 'types of dwelling'. Please select at least one.</h2>");
$('#linky').hide();
}
else if(data=="b"){
$('#content').html("<h2>You have not selected any 'style of dwelling'. Please select at least one.</h2>");
$('#linky').hide();
}
else if(data=="c"){
$('#content').html("<h2>You have not selected any 'situation of dwelling'. Please select at least one.</h2>");
$('#linky').hide();
}
else if(data==1){
$('#content').html('<h2>There is ' + data + ' property available!</h2>');
$('#linky').show();
}
else if(data==0){
$('#content').html('<h2>There are no properties available, please expand your search options.</h2>');
$('#linky').hide();
}
else{
$('#content').html('<h2>There are ' + data + ' properties available!</h2>');
$('#linky').show();
}
}//end processData
In the filtertest.php file, the following code is used to check if none of the field values are entered, and if so returns the letter a:
//if none of the TODs are selected, returns an error
if ($_GET[tod_house]==0 && $_GET[tod_bung]==0 && $_GET[tod_flat]==0 && $_GET[tod_barnc]==0 && $_GET[tod_farm]==0 && $_GET[tod_small]==0 && $_GET[tod_build]==0 && $_GET[tod_devland]==0 && $_GET[tod_farmland]==0 ){
echo "a";
return;
}
However in the initial ajax function processData the line beginningif(data =="a"){ isnt catching the value echoed - its going all the way down to the final else function. The strange thing is the letter 'a' is input into the html in this final else function, meaning the echo is correct and the filtertest.php file is returning immediatly - its just not being caught by the if function testing for the letter 'a'.
There must be some syntax error here but Ive been looking at it for the last hour trying different things and I cant work it out, its starting to really annoy me!!
edit
After changing the daft error pointed out below, it still wasnt working. I tried echoing a different number instead of a letter. I changed 'a' in both processData and filtertest.php to '-1' and HEY PRESTO! it works. So it is an error with the string containing 'a' - am I getting the comparison of two strings wrong in the javascript function?
The problem is how you try to access your data in the $_GET array: keys should be strings, i.e.
$_GET['tod_house']
not
$_GET[tod_house]
More precision coming from Marc B' comment: the output won't be just a and thus won't be picked.

cannot call replace of undefined in jQuery

I have a table listing values pulled from a database, I then gather up these values and save them into an array to be sent back to the database (with JSON) I'm using
$('#ing_table tr').each(function(row, tr){
ingredients[row] = {
"ing" : $(tr).find('input:eq(0)').val(),
"amt" : $(tr).find('input:eq(1)').val(),
"meas" : $(tr).find('option:selected').text()
};
});
to get this info. Generally everything works great except that a few of the strings that occasionally populate the 'ing' row have quotes (") which mess things up. I tried this:
$('#ing_table tr').each(function(row, tr){
ingredients[row] = {
"ing" : $(tr).find('input:eq(0)').val().replace('"', ' '),
"amt" : $(tr).find('input:eq(1)').val(),
"meas" : $(tr).find('option:selected').text()
};
});
but I get a 'cannot call method 'replace' of undefined'
Note: The above code is found in the function stroreIng() which returns ingredients. I used:
var recIng = storeIng();
recIng = $.toJSON(recIng);
this is where it added \\ before the " in the JSON
Any help would be appreciated
It seems that there simply isn't any input present for some rows. And in case of empty selectors val() returns undefined:
$().val() == undefined //true
so your replace method fails in such cases. You should use something like this:
$('#ing_table tr').each(function(row, tr){
ingredients[row] = {
"ing" : ($(tr).find('input:eq(0)').val() || "").replace('"', ' '),
"amt" : $(tr).find('input:eq(1)').val(),
"meas" : $(tr).find('option:selected').text()
};
});
I was unable to get the replace() method to work here, but I went to the php page and was able to use str_replace() to remove the escaped quote. Now everything works fine. Thanks for your help!

Categories

Resources