How can I pass values from javascript var to executeSql?
I wrote this code:
function BuscaRegistros() {
var mydata=document.getElementById("lugar").value;
var mydata2=document.getElementById("fecha").value;
var db = openDatabase('sightings03', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('SELECT CommonName FROM Sights03 WHERE location=**"mydata"** AND datte="**mydata2**"' , [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++){
document.despliega.desp.options[i]=new Option(results.rows.item(i).CommonName,i);
}
}, null);
});
}
Are you asking how to concatenate strings? You do that with the + operator.
In general it's like this:
var mydata = "hello";
var string = "the value is: " + mydata;
console.log(string); // the value is: hello
So you might do:
tx.executeSql('SELECT CommonName FROM Sights03 WHERE location="' + mydata + '" AND datte="' + mydata2 + "' , [], function (tx, results) {
Related
I have 2 different tables where the first table is used for retrieving the data to store in the second table, so for example, if there are 3 items in the first table, ill run a for loop 3 times to retrieve the information and storing it in the second table row by row, i also have to use a unique id for the primary key for the second table, so i have to run another mysql query to retrieve all the ID in the second table and add 1 to the id to generate a new ID, but the problem for me is that when i try to put a connection.query in another connection.query, the outer connection.query runs 3 time before running the inner connection.query, hence the items does not get stored and the id does not update, giving me a duplicate primary key error, i tried using functions but it doesnt help, here is
app.get('/submit-check', function (request, response) {
function insert(sql2) {
connection.query(sql2, function (err, result1) {
if (err) throw err;
});
}
function other(value, index) {
let sql = "SELECT * FROM ORDERS"
connection.query(sql, function (err, results) {
var id;
if (results.length == 0) {
id = 0
} else {
id = results[results.length - 1].orderID;
}
// for (let j = 0; j < results.length; j++) {
// list.push(results[j].orderID)
// }
// if (list.length == 0) {
// id = 0
// }
// else {
// var largest = 0;
// for (let i = 0; i <= list.length; i++) {
// if (parseInt(list[i]) > largest) {
// var largest = parseInt(list[i]);
// }
// }
// id = largest + 1
// }
id = id + 1;
var add = request.query.state + " " + request.query.address + " " + request.query.Unumber + " " + request.query.zip
var custID = value[index].custID
var bookID = value[index].bookID
var Email = request.query.email
var CardName = request.query.cardname
var CardNumber = request.query.cardnumber
var ExDate = request.query.expmonth + "/" + request.query.expyear
var CVV = request.query.cvv
var qty = 1
var sql2 = "INSERT INTO orders (orderID,custID, bookID, QTY, CardName, CardNumber, ExDate, CVV, Email, Address, createdAt, updatedAt) VALUES('" + id + "','" + custID + "', '" + bookID + "', '" + qty + "', '" + CardName + "', '" + CardNumber + "', '" + ExDate + "', '" + CVV + "', '" + Email + "', '" + add + "', CURDATE(), CURDATE() )"
insert(sql2)
})
}
function setValue(value) {
for (let index = 0; index < value.length; index++) {
other(value, index)
}
}
let sql3 = "SELECT * FROM carts"
var cart_db;
connection.query(sql3, function (err, result) {
cart_db = result
setValue(cart_db)
})
// console.log(cart_db)
response.render("aftercheck", { attributes: request.query, cardno: "****-****-****" + request.query.cardnumber.slice(-5,) });
})
thank you in advance
There are many, many things wrong with your code. I've peppered this await/async-based rewrite with TODO comments where you'll probably need to fix up things. Naturally I haven't been able to test this since I don't have your database.
async function queryP(connection, sql, parameters = undefined) {
return new Promise((resolve, reject) => {
connection.query(sql, parameters, function (err, results) {
if (err) return reject(err);
resolve(results);
});
});
}
app.get("/submit-check", async function (request, response) {
// TODO: these need to be validated
const {
address,
Unumber,
zip,
expyear,
state,
expmonth,
email: Email,
cardname: CardName,
cardnumber: CardNumber,
cvv: CVV,
} = request.query;
const add = `${state} ${address} ${Unumber} ${zip}`;
const ExDate = `${expmonth}/${expyear}`;
const cartData = await queryP(connection, "SELECT * FROM carts"); // TODO: this is not safe with multiple customers
const [maxOrderIdRow] = await queryP(connection, "SELECT MAX(id) as maxid FROM orders");
const orderId = (maxOrderIdRow.maxid || 0) + 1; // TODO: this is not safe in the face of concurrent requests
// Using a for loop rather than .map and await and so on is simpler here
for (let i = 0; i < cartData.length; i++) {
const cartRow = cartData[i];
const custID = cartRow.custID;
const bookID = cartRow.bookID;
const qty = 1;
// TODO: rethink how credit cards are saved – we can't save them in the database like this or we'll be out of business
await queryP(
connection,
`INSERT INTO orders (orderID, custID, bookID, QTY, CardName, CardNumber, ExDate, CVV, Email, Address, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), CURDATE() )`,
[orderId, custID, bookID, qty, CardName, CardNumber, ExDate, CVV, Email, add],
);
}
response.render("aftercheck", {
attributes: request.query,
cardno: "****-****-****" + CardNumber.slice(-5),
});
});
I have working scraper here but im struggling with sorting the data.
Here is the scraper code:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
http.createServer(function (req, res) {
request('http://www.xscores.com/soccer', function (error, response,
html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var list_items = "";
var arr = [];
var arr2 = [];
var j = 1;
$('div.match_line.score_row.other_match.e_true').each(function (i, element) {
var a = $(this).attr('data-home-team');
arr.push(a + " Row Number " + j);
j = j + 2;
//list_items += "<li>" + a + "</li>";
//console.log(arr.length);
});
var j = 2;
$('div.match_line.score_row.other_match.o_true').each(function (i, element) {
var b = $(this).attr('data-home-team');
arr.push(b + " Row Number " + j);
j = j + 2;
//list_items += "<li>" + b + "</li>";
//console.log(arr.length);
});
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
list_items += "<li>" + arr[i] + "</li>";
}
var html = "<ul>" + list_items + "</ul>"
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(html);
console.log(arr.length);
}
});
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');
So to the problem, Sorting these elements.
Element 'div.match_line.score_row.other_match.e_true' are in placed every nth
Odd Row Number in the source page.
And element 'div.match_line.score_row.other_match.o_true' are in placed every nth Even Row Number in the source page.
The way It gets sorted now
My array(arr) first pushes all rows of data into the array from the first
element (odd row number)
Then array(arr) pushes all rows of data from the 2nd element into the same
array. (even row number)
So basically items in my array is sorted like this 1,3,5,7,9,2,4,6,8 (shortened)
How can I sort this so I can output this in correct order ?
Any suggestion for a solution would be much appreciated
Frederik
Check the arr.sort method below.
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
http.createServer(function(req, res) {
request('http://www.xscores.com/soccer', function(error, response,
html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var list_items = "";
var arr = [];
var arr2 = [];
var j = 1;
$('div.match_line.score_row.other_match.e_true').each(function(i, element) {
var a = $(this).attr('data-home-team');
arr.push({
html: a,
j: j
});
j = j + 2;
//list_items += "<li>" + a + "</li>";
//console.log(arr.length);
});
var j = 2;
$('div.match_line.score_row.other_match.o_true').each(function(i, element) {
var b = $(this).attr('data-home-team');
arr.push({
html: b,
j: j
});
j = j + 2;
//list_items += "<li>" + b + "</li>";
//console.log(arr.length);
});
arr.sort(function(a, b) {
return a.j - b.j
})
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
list_items += "<li>" + arr[i].html + "</li>";
}
var html = "<ul>" + list_items + "</ul>"
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(html);
console.log(arr.length);
}
});
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');
Hi i´m trying to convert sqlite database to NeDb, with this code:
const sqliteJSON = require('sqlite-json');
const Datastore = require('nedb')
const exporter = sqliteJSON('etecsa.db');
db = new Datastore('etecsa.nedb');
db.loadDatabase();
tables = ['fix','movil'];
tables.forEach(function(table) {
sql = 'select count(1) from ' + table;
exporter.json(sql, function (err, json) {
toNeDB(table, JSON.parse(json)[0]['count(1)'])
});
}, this);
var toNeDB = function(table, count) {
var inc = 10000;
console.log(table + ' => ' + count)
for (var i = 0; i < count + inc; i += inc) {
var sql = 'SELECT * FROM ' + table + ' ORDER BY province ASC, number DESC LIMIT '+ i + ' , ' + inc;
console.log(i)
exporter.json(sql, function(err, json) {
var data = JSON.parse(json);
db.insert(data, function (err, newDoc) {});
});
}
}
the problem is that the for loop its not working as I desire. I need to use it to change the sql pagination because the sqlite database is very huge and I can´t pass all the data on a single query.
UPDATE using async.map
const sqliteJSON = require('sqlite-json');
const Datastore = require('nedb')
var range = require("range");
var async = require("async");
const exporter = sqliteJSON('etecsa.db');
db = new Datastore('etecsa.nedb');
db.loadDatabase();
tables = ['fix','movil'];
tables.forEach(function(table) {
sql = 'select count(1) from ' + table;
exporter.json(sql, function (err, json) {
toNeDB(table, JSON.parse(json)[0]['count(1)'])
});
}, this);
var toNeDB = function(table, count, cb) {
var inc = 10000;
var pagination = range.range(1,count+inc,inc)
async.map(pagination, function (page, cb){
var sql = 'SELECT * FROM ' + table + ' ORDER BY province ASC, number DESC LIMIT '+ page + ' , ' + inc;
console.log(page, table, inc);
exporter.json(sql, function(err, json) {
var data = JSON.parse(json);
console.log(data[0])
db.insert(data, function (err, newDoc) {});
});
}.bind({ table: table, inc: inc }), function(err,results){
})
}
and the output:
1 'fix' 10000
10001 'fix' 10000
....
1150001 'fix' 10000
1 'movil' 10000
10001 'movil' 10000
...
3730001 'movil' 10000
{ number: '8775031',
name: 'UNION ELECTRICA',
address: 'S ALLENDE #666 OQUENDO SOLEDAD',
province: 7 }
{ number: '8734454',
name: 'EMP ESTB ESP Y SERVICIOS',
address: 'ESAPDA #256 CONCORDIA S LAZARO',
province: 7 }
If you need to know when each action occurred, you should put the console.log inside the callback.
Something like that:
var toNeDB = function(table, count) {
var inc = 10000;
console.log(table + ' => ' + count)
for (var i = 0; i < count + inc; i += inc) {
var sql = 'SELECT * FROM ' + table + ' ORDER BY province ASC, number DESC LIMIT '+ i + ' , ' + inc;
exporter.json(sql, (function(i) {
return function(err, json) {
console.log(i)
var data = JSON.parse(json);
db.insert(data, function (err, newDoc) {});
}
})(i));
}
}
You could use recursion instead of a loop, that way you would be sure the next iteration won't execute until the first is done.
var proc = function (i, count, table) {
var sql = 'SELECT * FROM ' + table + ' ORDER BY province ASC, number DESC
LIMIT ' + i + ' , ' + inc'
console.log(i)
exporter.json(sql, function (err, json) {
var data = JSON.parse(json)
db.insert(data, function (err, newDoc) {
if (i < count) {
i += inc
proc(i, count, table)
}
})
})
}
var toNeDB = function (table, count) {
var inc = 10000
console.log(table + ' => ' + count)
proc(0, count, table)
}
let me know if that works
I have an array in php which i am getting in Javascript.
Here is my php code
$query = "SELECT SeatNum FROM `$busNum` WHERE AB = 1";
$runQuery = mysqli_query($con, $query);
$i = 0;
foreach($runQuery as $row)
{
$availableSeats[$i++] = $row['SeatNum'];
}
And here i am getting this string in javascript
var getBookedSeats = <?php echo json_encode($availableSeats); ?>;
var bookedSeats =[];
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = getBookedSeats[i];
}
The array also saved in bookedSeats successfully. Now the problem is that when i used that array as a parameter to call function. Nothing goes in the parameter. Even there is no problem of scope. This is my function looks like:
var init = function (reservedSeat) {
//code
}
init(bookedSeats);
Implementation of init function is :
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
Seems the problem is that you are trying to compare the array values as numbers and you currently have them as strings. To convert them to numbers, you can simply use:
bookedSeats = bookedSeats.map(Number) // iterate over each bookedSeats element and return its numeric value
Which is the same as:
bookedSeats = bookedSeats.map(function(value){
return Number(value);
})
From the comments it looks like your variable bookedSeats is being assigned with values. However, if your init() function is expecting integers, you'll want to build the bookedSeats array with integers like so:
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = parseInt( getBookedSeats[i], 10 );
}
I do not use php but I belive php's json_encode returns a JSON formatted string. Which results in your JavaScript code storing individual characters from the string into the bookSeats variable.
You need to parse the string returned from php. For example...
var getBookedSeats = JSON.parse(<?php echo json_encode($availableSeats); ?>);
I have a phonegap db functioning JS script below. I want to return the final string variable "feeds" outside the whole function. This only returns "undefined". Please help me with required changes to return the "feeds" variable.`
function getProviders() {
var feeds = "";
var db = window.openDatabase("db", "1.0", "desc", 1000000);
db.transaction(function(tx) {
var db = window.openDatabase("db", "1.0", "desc", 1000000);
tx.executeSql("SELECT * FROM `feed_provider`", [], function(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
feeds += results.rows.item(i).id + "|" + results.rows.item(i).name + "|" + results.rows.item(i).status + "|" + results.rows.item(i).feed_url + ",";
}
}, sqlerror);
}, sqlerror2);
return feeds;
}
I'm going to assume either db.transaction or tx.executeSql is async, in which case I would use a deferred:
function getProviders() {
var feeds = "";
var def = $.Deferred();
var db = window.openDatabase("db", "1.0", "desc", 1000000);
db.transaction(function(tx) {
var db = window.openDatabase("db", "1.0", "desc", 1000000);
tx.executeSql("SELECT * FROM `feed_provider`", [], function(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
feeds += results.rows.item(i).id + "|" + results.rows.item(i).name + "|" + results.rows.item(i).status + "|" + results.rows.item(i).feed_url + ",";
}
def.resolve(feeds);
}, sqlerror);
}, sqlerror2);
return def.promise();
}
Call it like this:
getProviders().done(function(feeds) {
// do something with feeds
});