Home > database >  Fetch multiple rows of a single column and assign them to different variables in an array in php
Fetch multiple rows of a single column and assign them to different variables in an array in php

Time:11-13

i want to take value of all the subjects on year 2019 one by one and assign them in a variable like $sub1, $sub2 from the following table. how can i do so? database

the query i am using is as follows

 $sql="SELECT * FROM `Regular Subjects` where Year='$year'";
 $r=$con->query($sql);

if($r->num_rows>0){
 while($subjects=$r->fetch_assoc(){

 $sub=$subjects["Subject"];
 echo $sub;

};

CodePudding user response:

You can use an array say known as $data to store the data so that you can retrieve it later

Assuming that your code is correct so that it can retrieve the data as $subjects["Subject"] in the loop

Then change the block:

while($subjects=$r->fetch_assoc(){
 $sub=$subjects["Subject"];
 echo $sub;
};

to

$data = array();
$index=1;

while($subjects=$r->fetch_assoc(){
 $subx=$subjects["Subject"];
// echo $sub;
 $data["sub".$index]=$subx;
 $index  ;
};

Then you will have the data stored in $data["sub1"], $data["sub2"]... and so on

  • Related