简体   繁体   中英

Double and Single quotes on Insert SQL

I'm trying to insert dynamic elements to a table using Javascript and SQLite, I have a problem when one of the values has a single quote AND a double quote, for example -- 7' inches" vinyl -- I KNOW THAT EXAMPLE MAKES NO SENSE, but the users of this app insert all kind of crap in the forms.

My query would be messed up with the "' everywhere, my question is: is there a function or something that could make me use the real string that I need without breaking everything?

This is the code:

$.each(data, function(i, item) {   
                tx.executeSql("INSERT INTO articulo (codart) VALUES (" + validate(item.CODART) + ")");
});


function validate(item){
        if(item == null){
            return null;
        }else{
            return "'" + item + "'";
        }
    }

您可以通过将单引号加倍来转义单引号,但仅使用参数会更容易:

tx.executeSql("INSERT INTO articulo (codart) VALUES (?)", [validate(item.CODART)]);

The double quotes should not create a problem. Try replacing the single quotes by two single quotes.

Change the function to:

function validate(item){
    if(item == null){
        return null;
    }else{
        return "'" + item.replace("'", "''") + "'";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM