Question

I use the following to display, with innerHTML, the Javascript-based webSQL data (containing 4 fields) on the HTML page:

var rowid = results.rows.item(i).id;
document.getElementById("output2").innerHTML += "<table><tr><td><index type='button' class='buttonDel' onclick='delRecord(\"" + rowid + "\")' value='Delete'>" + results.rows.item(i).id + "</td><td>" + results.rows.item(i).data1 + "</td><td>" + results.rows.item(i).data2 + "</td><td>" + results.rows.item(i).data3 + "</td></tr></table>";

A red Delete button appears in the ID column of the HTML table with the correct id put into var rowid (confirmed with an alert). The button calls the following functions to delete the record. Of course, that doesn't happen.

// Delete a row in the DB

function delRecord(rowid) {
    var db = window.openDatabase("Database", "1.0", "DEMO", 2000000);
    db.transaction(delDB, errorCB, successCB);
}
function delDB(tx) {
    tx.executeSql("DELETE from DEMO WHERE id == rowid"); 
}

What is the correct syntax to delete the record?

Here's how the buttons are being formatted:

function querySuccess(tx, results) {
    var len = results.rows.length;
    console.log("Returned rows = " + results.rows.length);
for (var i = 0; i < len; i++) { 
var rowid = results.rows.item(i).id;
                document.getElementById("output2").innerHTML += 
    "<table><tr><td><index type='button' class='buttonDel' onclick='delRecord(\"" + 
    rowid + "\")' value='Delete'>" + 
        results.rows.item(i).id + 
        "</td><td>" + results.rows.item(i).data1 + 
        "</td><td>" + results.rows.item(i).data2 + 
        "</td><td>" + results.rows.item(i).data3 + "</td></tr></table>";
                }
Was it helpful?

Solution

The correct syntax is DELETE FROM tableName [WHERE expr] (The underlying implementations all use SQLite, AFAIK.)

However, there are several related problems:

  1. The condition used is wrong, SQL uses = for equality.

  2. rowid, as string content, is wrong. That will never be the ID because no "magic replacement" is done. Instead, use a parameterized query and specify the bound value.

Consider:

function deleteRecord(rowid) {
    var db = getCurrentDatabase();
    db.transaction(
      function (tx) {
        tx.executeSql("DELETE FROM demo WHERE id = ?", [rowid]); 
      });
}

I also used a closure to make rowid readily accessible. Refer to some tutorials for more general and examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top