SQL Injection Safe Query Builder
Build parameterized SQL queries with explicit placeholders to prevent injection while supporting dynamic WHERE and ORDER BY.
Code
export function queryBuilder(table){let whereClauses=[],params=[],orderBy=null;function where(col,op,val){whereClauses.push(col+' '+op+' ?');params.push(val);return api;}function whereIn(col,vals){whereClauses.push(col+' IN ('+vals.map(()=>'?').join(', ')+')');params.push(...vals);return api;}function order(col,dir='ASC'){if(!['ASC','DESC'].includes(dir.toUpperCase()))throw new Error('invalid direction');orderBy='ORDER BY '+col+' '+dir.toUpperCase();return api;}const api={where,whereIn,order,build(){const w=whereClauses.length?'WHERE '+whereClauses.join(' AND '):'';return{sql:('SELECT * FROM '+table+' '+w+' '+(orderBy??'')).trim(),params};}};return api;}Report a problem with this exampleOpens a pre-filled issue on GitHub.