Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I escape SQL query's single quotes for query generated in javascript/jquery in cartodb database?
    primarykey
    data
    text
    <p>I am using javascript/jquery to generate a sql query. I have a sql query I'm generating and using inside a javascript/jquery script.</p> <p>Something like this:</p> <pre><code>var storeName; var query = "SELECT * FROM stores where storeName = '" + storeName + "';"; </code></pre> <p>(<code>storeName</code> is generated through jquery when a user selects from html)</p> <p>So when <code>storeName</code> is something like <strong>"Jackson Deli"</strong> the query runs just fine.</p> <p>But then when <code>storeName</code> is <strong>"Jackson's Deli"</strong> it does not work and it seems to be because the apostrophe in <strong>Jackson's</strong> is treated like a closing quote. I know I can escape a quote by doubling it if I was hard-coding the query... so </p> <pre><code>SELECT * FROM stores where storeName = 'Jackson''s Deli'; </code></pre> <p>should work. But I'm not hard-coding the query. Instead it's being generated by user input and may or may not have an apostrophe in the name. How would I go about escaping <code>'</code> this character in this case? I would need it to work inside Javascript/jquery.</p> <p>Would I need to write an if statement that looks for <code>'</code> in <code>storeName</code> and replaces it with <code>''</code> ?? Or is there another way to go about this?</p> <p>EDIT: Ouch! Normally, yes, I realize the perils of generating a query on the client side.<br> So here's some more context. I'm working with <a href="http://www.cartodb.com" rel="nofollow">cartodb</a> and following their documentation. Here's an example from their repo doing something similar to what I'm talking about (they have other examples too):</p> <p><a href="https://github.com/CartoDB/cartodb.js/blob/develop/examples/layer_selector.html" rel="nofollow">https://github.com/CartoDB/cartodb.js/blob/develop/examples/layer_selector.html</a></p> <p>You can't run a query in cartodb that lets you modify data in any way -- you can only run queries that let you retrieve data. So I'm still thinking about what the best way to escape this quote character would be.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload