Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unknown column in where clause in NextJS API

I’m writing an API which would fetch data from a MySQL table based on a category. The code currently looks like this.

import { sql_query } from "../../../lib/db"

export default async function handler(req, res) {
    var category = 'Starters'
    if (req.method === 'GET') {
        try {
            const results = await sql_query({
                query_string: `SELECT * FROM products WHERE category = ${category}`
            })
            return res.status(200).json(results)
        } catch (error) {
            res.status(500).json({ message: error.message })
        }
    }
}

This isn’t going through for some reason and instead, I see this error message

{"message":"ER_BAD_FIELD_ERROR: Unknown column ‘Starters’ in ‘where
clause’"}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

From what I know, my MySQL query is fine because it works okay in PHPMyAdmin. Can anyone point out what I’m doing wrong here?

>Solution :

The error suggests the parameter is being injected and used in the context of a column name, you probably need quotes:

`SELECT * FROM products WHERE category = '${category}'`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading