user25
user25

Reputation: 141

How to get data from database in javascript based on the value passed to the function

In my web application, I want to retrieve data from database based on the value that is passed to the function. I wrote the query as follows.

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = parseInt(val);',[], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

In body tag,

<body>
   ---
     <a href = "#" onClick = "javascript:getSelectedRow('1')>getValues</a>

I got the problem while retrieving data from database, i.e., at SELECT query. It doesn't accept the value parseInt(val), if I give the condition as 'name = 1' it simply accepts the condition and give the result, but it doesn't accept 'name = parseInt(val)' and throws error as 'no such column: val code: 1' Please tell me how to pass value in 'val'.. Thanks in Advance..

Upvotes: 3

Views: 132952

Answers (3)

DThought
DThought

Reputation: 1314

Try the following:

<script> 
 //Functions to open database and to create, insert data into tables

 getSelectedRow = function(val)
    {
        db.transaction(function(transaction) {
              transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);

        });
    };
    selectedRowValues = function(transaction,results)
    {
         for(var i = 0; i < results.rows.length; i++)
         {
             var row = results.rows.item(i);
             alert(row['number']);
             alert(row['name']);                 
         }
    };
</script>

You don't have access to javascript variable names in SQL, you must pass the values to the Database.

Upvotes: 1

Ankit Jajoo
Ankit Jajoo

Reputation: 910

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

Upvotes: 2

Esailija
Esailija

Reputation: 140210

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

Upvotes: 2

Related Questions