Bwyss
Bwyss

Reputation: 1834

Loop through array and add parameters to sql query in javascript

I want to assign an sql sting to a variable in Javascript. But I want to loop through an array to build par of the sql statement.

static sql:

var tag = [fun, beach, sun];

var sql = "SELECT * FROM myTable "
            +"WHERE id > 5" //...
            // loop through tag array and add to the sql
            function tagQuery(tag) {
                for (var i = 0; i < tag.length; i++) {
                var tagQuery = "AND WHERE tags like %'"+tag[i]+"'%";
                return tagQuery;
                }; 
            }

It is not clear to me how to get each result of the tagQuery function to be added to the sql sting?

EDIT: maybe a more clear way to ask the question is: How can I get each iteration of the tagQuery function to be joined with the sql variable?

Upvotes: 0

Views: 2301

Answers (2)

Doug_Ivison
Doug_Ivison

Reputation: 650

EDIT:
I took out the tagQuery function altogether, after you commented:
sql += tagQuery(tag); ...will only return the last iteration of the tagQuery loop

var tag = ['fun', 'beach', 'sun'];
var sql = "SELECT * FROM myTable WHERE id > 5";

if (tag[0] != null) {
    sql += " AND (tags like '%" + tag[0] + "%' "; 
}

if (tag[1] != null) {
    for (var i = 1; i < tag.length; i++) {
        sql += " OR tags like '%" + tag[i] + "%' ";
    }
}

if (tag[0] != null) {
    sql += ")";
}

But note: the jsFiddle link that Rusty put in a comment, since, shows that the tagQuery function can return all iterations... so seeing only the last iteration was probably in your implementation.

Upvotes: 0

Rusty Fausak
Rusty Fausak

Reputation: 7525

var tag = [fun, beach, sun];

var sql = "SELECT * FROM myTable WHERE id > 5";

function tagQuery(tag) {
    var str = '';
    for (var i = 0; i < tag.length; i++) {
        str += " AND tags like '%" + tag[i] + "%' "
    }
    return str;
}

sql += tagQuery(tag);

Fiddle: http://jsfiddle.net/7P4us/2/

Upvotes: 2

Related Questions