Hi i want to select values between 2 number in php and i want to check if all of them exist in DB and there is no error but when i dump it is says array = 0
I am trying to get question and options in a single query using inner join and select them between 2 numbers ,i check if they are in db with IN i get the first number and then i add 6 to it and then generate all numbers between them to use for IN
public function selectquestion($id){
$max = $id + 4;//max selected value
for ($i=$id; $i<=$max; $i++) {
$arr[] = $i;//generates all numbers between min and max
}
$range = implode(",",$arr);
$sql = $this->pdo->prepare("SELECT questions.value,questions.file,questions.img,options.option1,options.option2,options.option3,options.option4,options.answer
FROM options
INNER JOIN questions
ON questions.id = options.q_id
WHERE questions.id >= '$id'
AND questions.id <= '$max'
AND questions.id IN ($range)");//selects all of questions and options where condition is true
$row = $sql->fetchAll(PDO::FETCH_OBJ);
return$row;
}
var_dump($options = $obj->selectquestion(2));
i want it to show all questions and options but the output is 0
Your main issue is that you never execute the query. You should also be using a prepared statement instead of injecting your variables directly into the query.
It also makes little sens to check both for an ID to be greater than minimum, less than maximum and within that range. You can simplify your query and use a proper prepared statement by just checking the BETWEEN
instead. Also, by using aliases you can shorten down the columns you select.
public function selectquestion($id){
$max = $id + 4; //max selected value
$sql = $this->pdo->prepare("SELECT q.value, q.file, q.img,
o.option1, o.option2, o.option3, o.option4, o.answer
FROM options o
INNER JOIN questions q
ON q.id = o.q_id
WHERE q.id BETWEEN ? AND ?");
$sql->execute([$id, $max]);
return $sql->fetchAll(PDO::FETCH_OBJ);
}