Home > Blockchain >  Unknown column in where clause in NextJS API
Unknown column in where clause in NextJS API

Time:05-08

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'"}

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?

CodePudding user response:

The error indicates the parameter is being injected and used in the context of a column name, you need to contain it within quotes:

`SELECT * FROM products WHERE category = '${category}'`
  • Related