HTML and CSS Reference
In-Depth Information
The
INSERT
statement is the most important part, and now you
can see how the fi eld arguments work:
tx.executeSql('INSERT INTO tweets (id, screen_name, date,
¬
text) VALUES (?, ?, ?, ?)', [tweet.id, tweet.from_user,
¬
time / 1000, tweet.text]);
Each “?” in the
INSERT
statement maps to an item in the array that
is passed in as the second parameter to
executeSql
. So the first
“?” maps to
tweet.id
, the second to
tweet.from_user
, and so on.
Yo u c a n a l is o is e e t h a t I ' v e d i v i d e d t h e t i m e b y 1 0 0 0 ; t h i is i is
because JavaScript time goes to milliseconds, whereas SQLite
doesn't. SQLite goes down to whole seconds. This is only
important for your query later on in the code where you show
tweets that are 5 minutes old. This matters because you're
storing dates as integers, and one second using JavaScript's
getTime
method gives us 1000, whereas one second using
SQLite gives us 1. So you divide by 1000 to store seconds rather
than milliseconds.
Finally, when the radio buttons are clicked, you call the
show
function with the amount of time as the argument:
var tweetEl = document.getElementById('tweets');
function show(amount) {
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM tweets' + (amount !=
¬
'all' ? ' WHERE date > strftime(“%s”, “now”, “-' +
¬
amount + ' minutes”)' : ''), [], function
¬
(tx, results) {
var html = [],
len = results.rows.length;
for (var i = 0; i < len; i++) {
html.push('<li>' + results.rows.item(i).text +
¬
'</li>');
}
tweetEl.innerHTML = html.join('');
});
});
}
On initial review this code may look complicated, but there are
actually only a couple of things happening here:
1.
Start a new transaction
2.
Run a single SQL statement, whose structure is determined
by whether you want “all” or not