0

I'm new on php and mysql. I found several things that I can use - such as implode- on internet but I couldn't make it. I will try to be clear as much as I can.

First table name: mylist

column name: id (The values on this column are unique.) (incremental)

I put all ids inside an array called myIds. The array contains only unique integer values and it's length is 800.

I need to get answers for each ids from another table for the current date. This table also contain id column but for an id, there can be more than one answer.

For example: today, there are 3 answers for id 1 and 5 answers for id 4, etc.

Second table name: answerlist

This is the query works for a specified id:

$sql = "SELECT `answer` FROM `answerlist` WHERE `type`= 'Help' AND `id` = 1 AND DATE(`added`) = DATE (NOW())";

I would like to create a dynamic query which gets id values from the above array. How can I do this?

Papipone
  • 1,083
  • 3
  • 20
  • 39
Catty
  • 1
  • 2
  • Which mysql driver are you using? mysqli or PDO ? – YouneL Sep 30 '18 at 19:29
  • Possible duplicate of [PHP - Using PDO with IN clause array](https://stackoverflow.com/questions/14767530/php-using-pdo-with-in-clause-array) – YouneL Sep 30 '18 at 19:30

1 Answers1

0

A Solution would be to use The mysql IN operations for your ids

SELECT `answer`, `id` FROM `answerlist` WHERE `type`= 'Help' AND `id` IN (1,2,3,4,5) AND DATE(`added`) = DATE (NOW())

you can implode them like this :

$sql = "SELECT `answer`, `id` FROM `answerlist` WHERE `type`= 'Help' AND `id` IN (" . implode(',', $myIds) . ") AND DATE(`added`) = DATE (NOW())";
BlackNetworkBit
  • 768
  • 11
  • 21
  • 1
    I think your solution is vulnerable to [SQL injection](https://en.wikipedia.org/wiki/SQL_injection), you should use prepared query instead – YouneL Sep 30 '18 at 19:32
  • That is kind of correct if the User can change the ids, i just went with the idea that this is not the case. IF The user can change the ids then indeed he should check out https://stackoverflow.com/questions/772913/how-do-you-use-in-clauses-with-mysqli-prepared-statements – BlackNetworkBit Sep 30 '18 at 19:34