Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js mysql query where id = ARRAY?

I am working to fetch data of listed users and I have an array of users like

var result_user_id = [
  {
    "id": 19
  },
  {
    "id": 20
  }
];

and I tried something like

connection.query( 
   "select * from `contents` where `user_is` IN "+ result_user_id, 
   function( err_user, result_user ) {

   }
);

but unable to fetch related data. how to do that in node js.

like image 585
iam Avatar asked Nov 28 '22 16:11

iam


2 Answers

var o =[
  {
    "id": 19
  },
  {
    "id": 20
  }
];
var arr = o.map( function(el) { return el.id; });
connection.query( "select * from `contents` where `user_is` IN ("+ connection.escape(arr)+")", function( err_user, result_user ) { });

input can be sanitized using connection.escape(), mysql.escape() or pool.escape(). please refer this to sanitize input.

like image 173
Vishnu Avatar answered Dec 01 '22 00:12

Vishnu


I know this question is a little bit older, but I found it via googled and stumbled across the same problem. This is the easiest solution I found:

    var result_user_id = [
  {
    "id": 19
  },
  {
    "id": 20
  }
];

var result_array = [];

  for (var i = 0; i < result_user_id; i++) {
      result_array[i] = result_user_id[i].id;
    }

connection.query( "select * from contents where user_is IN (?)", [result_array], function( err_user, result_user ) { });
like image 45
Tyler Edman Avatar answered Dec 01 '22 00:12

Tyler Edman