Jack Stern Jack Stern - 5 months ago 10
SQL Question

How to insert data between mysql fetched result in php?

I'm trying to insert a new predefined data after 6th line while fetching result from mysql in php. After that, I want to insert a predefined text after every 5th line.

while($row=mysql_fetch_array($result))
{

if((($i%6)== 0)&&($i!=0))
{

$emparray['category'] = "PREDEFINED DATA";
array_push($json_response,$emparray);

}

//Data from the database
$emparray['category'] = ucwords($row["tag"]);
array_push($json_response,$emparray);
++$i;
}


This is my code that I had managed but it gives me "PREDEFINED DATA" after every 6th line. What I want is that after 6th line message should be shown after every 5th line.

SML SML
Answer

If you want the value of key ['category'] of the associative array $emparray to be assigned as predefined data instead of the fetched result $row['tag'] at the 6th, 11th, 17th place and so on, the below code would give you the desired result.

$i=1;
while($row=mysql_fetch_array($result)){
   if(($i%6)==0){
     $emparray['category'] = "PREDEFINED DATA";
   }
   else{
//Data from the database
     $emparray['category'] = ucwords($row["tag"]);
   }
   array_push($json_response,$emparray);
   $i++;
}

If you want to add predefined data to the 6th, 11th, 17th place, and push the 6th fetched result $row['tag'] to the 7th place, you should do it like this.

$i=1;
while($row=mysql_fetch_array($result)){
   if(($i%6)==0){
     $emparray['category'] = "PREDEFINED DATA";
     array_push($json_response,$emparray);
   }
   else{
//Data from the database
     $emparray['category'] = ucwords($row["tag"]);
     array_push($json_response,$emparray);
   }
   $i++;
}

If you want predefined data to be added at the 6th, 11th, 17th place, in addition to the 6th, 11th, 17th value of the fetched result $row["tag"], you are approaching this wrongly as you can't assign two values to a key, you would need to make $emparray['category'] a subarray i.e. $emparray['category'][] instead.

Comments