0

I'm trying to return the results from a function I created. When I console.log(results) I can see the DB results, however for some reason it does not get returned by the function.

const get_non_showing_stores = (field_name) => {
    const connection = mysql_conn();
    const query = `SELECT * from stores WHERE ${field_name} = 0`;
    
    connection.query(query,(err,results) => {
      return results;
    });
};
karel
  • 5,489
  • 46
  • 45
  • 50
json2021
  • 2,146
  • 2
  • 14
  • 28
  • Duplicate of [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – esqew Nov 13 '21 at 00:01

1 Answers1

0

In JavaScript, the string looks like this:

`SELECT * from stores WHERE ${field_name} = 0 `;

When parsed in SQL, it looks like this:

SELECT * from stores WHERE someFieldName = 0 `;

Where ${field_name} is returning whatever field_name is, so in SQL, this is a syntax error where "someFieldName" is not defined.

You need to put quote marks around your query:

const get_non_showing_stores = (field_name) => {
    const connection = mysql_conn();
    const query = `SELECT * from stores WHERE '${field_name}' = 0;`;
     connection.query(query, (err, results) => {
        return results;
    });
};

Edit: It seems like you're trying to return the result of selection field_name. The "field_name" you are calling in the function, mat not be defined in your SQL Database.

Also, you are returning the value from connection.query, inside the function. You can not return a value from a child function / event listener.

You will need to call connection.query inside the place of code you are calling the function get_non_showing_stores(), then do what you want with the return value.

Another good SQL syntax tip: You should capitalize all built-in SQL syntax. Right here:

SELECT * from stores WHERE ${field_name} = 0;
         ^^^^
 Missing capitalization

And always should put a semicolon at the end of syntax:

SELECT * FROM stores WHERE ${field_name} = 0
                                            ^
                                    Missing semicolon
Parking Master
  • 551
  • 1
  • 4
  • 20
  • Thanks for your response. I am little confused when you said this – json2021 Nov 13 '21 at 01:38
  • You will need to call connection.query inside the place of code you are calling the function get_non_showing_stores(), then do what you want with the return value.... Can you show me an example? – json2021 Nov 13 '21 at 01:38