Jump to content

creating a list with database values…


thara

Recommended Posts

I am trying to print a list something like this....

[indent]
Catagory 01
  subjects1   subjects4
  subjects2   subjects5
  subjects3   subjects6

Catagory 02
  subjects1   subjects4
  subjects2   subjects5
  subjects3   subjects6

Catagory 03
  subjects1   subjects4
  subjects2   subjects5
  subjects3   subjects6[/indent]

 

One category has its own subjects. At the moment I have the category id and created a query to get its category name and its owned subjects. this is the query that I have created..

$categoryIds = implode(',', $_SESSION['category']);

$q = "SELECT c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si
FROM category AS c
INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id
INNER JOIN subjects AS s ON s.subject_id = cs.subject_id
WHERE c.category_id IN ($categoryIds)";

$r = mysqli_query( $dbc, $q) ;

 

Above query gives every categories and it own subjects. Its like a multidimensional array. My problem is I tried to print this date something like above list... But can not get it to work..

Is there someone to help me to this? Your ideas and comments are greatly appreciated.

Thank you.

Link to comment
Share on other sites

Christian F thanks for your reply. Its working... But My problem is I am going print category's subjects in a table with 2 columns. There is the place I have got stuck..

 

 

    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

       echo '<div>';

       if ( $catID != $row['ci']) {

           echo '<h3>Category 01: <span>' . $row['cn'] . '</span><span></span></h3>';
       }

       echo '<div class="container">';

           echo '<p>' . $row['sn']. '</p>'; // This subjects I need to display in a table with 2 columns..

       $catID = $row['ci'];

           echo '</div>';

       echo '</div>';
   }

 

can you tell me how I can do this? I tried something like this but its not working...

 

$catID = false;
$max_columns = 2;

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

$categoryId = $row['ci'];
$category = $row['cn'];

//Detect change in category
if($catID != $row['ci'])
{
if($catID!=false)
{
if($recCount % $max_columns != 0)
{
//Close previous row
echo "</tr>\n";
}
//Close previous table
echo "</table>\n";
}

$catID = $row['ci'];
echo "<div>\n";
echo "<h3>Category 01: <span>{$category}</span><span></span></h3>\n";
echo "<div class='container'>\n";
echo "<table><tr>\n";
$recCount = 0;
}

$recCount++;

if($recCount % $max_columns == 1)
{
echo "<tr>\n";
}

$value = "{$row['ci']}:{$category}:{$row['si']}:{$row['sn']}";
echo "<td width='50%'>";
echo "<input type='checkbox' name='subject[]' value='{$value}' />{$row['sn']}";
echo "</td>\n";

if($recCount % $max_columns == 0)
{
echo "</tr>\n";
}

if($recCount % $max_columns != 0)
{
//Close last row
echo "</tr>\n";
}
//Close last table
echo "</table>\n";

echo "</div></div>";
}
}

?>

Edited by thara
Link to comment
Share on other sites

I'm afraid you've overcomplicated this one a bit, which is causing some of the difficulties you have.

 

First of all, I don't think you need a table for this one, at least not according to the other markup in your code. In fact, most of what you added in your second code block is not necessary at all, so I recommend going back to the code in the first block.

 

The next step would be to use variables to build your output into, instead of echoing it out directly. This step will help to remove the artificial limitation in your code, which caused you most of the problems with what you want to do.

As I wrote in a post earlier today, it often pays to organize your code to manipulate data in a grouped manner. Contrary to what you have now, where you're processing and displaying the data in the same step.

 

So, now that you're saving your data to a temporary output variable, instead of displaying it straight away, it's time to bring in an old friend: The modulus operator.

Normally used to alternate a colour/class on elements, but also possible to use it to alternate where you save things. ;)

Link to comment
Share on other sites

my HTML design something like this...

 

<div>
 <h3>Category 01: <span>Information Technology</span><span></span></h3>
 <div class="container">

   <table>
     <tr>
       <td width="50%">
           <input type="checkbox" value="1" name="category[]">Subject1
       </td>
       <td width="50%">
           <input type="checkbox" value="2" name="category[]">Subject4
       </td>
     </tr>                                    
     <tr>
       <td width="50%">
           <input type="checkbox" value="1" name="category[]">Subject2
       </td>
       <td width="50%">
           <input type="checkbox" value="2" name="category[]">Subject5
       </td>
     </tr>                                    
     <tr>
       <td width="50%">
           <input type="checkbox" value="1" name="category[]">Subject3
       </td>
       <td width="50%">
           <input type="checkbox" value="2" name="category[]">Subject6
       </td>
     </tr>                                                        
   </table>                        
 </div>
</div>

Link to comment
Share on other sites

Yeah, that's what I thought.

From a semantic standpoint that makes no sense, with both subject 4 and 5 before subject 3. Better to use two DIVS, one with subject 1-3 and the other with subject 4-5, listed in that order. Then float them to the left, and give them both 50% width (with no margins and/or paddings)

Link to comment
Share on other sites

This is a DIV solution using my tables (in your case substitute category for pupil). I used a left margin on the divs to give the indent and separation.

 

<?php
include("tuteDBconnect.php");

$numcols = 2;	   // define how many columns of subjects

$sql = "SELECT p.pupil_name, s.subject
    FROM pupil p
    INNER JOIN choice c USING (pupilID)
    INNER JOIN subject s USING (subjectID)
    ORDER BY p.pupil_name, subject";
$res = $mysqli->query($sql);
$prev = '';
while (list($pupil, $subject) = $res->fetch_row()) {
   if ($pupil != $prev) {
    if ($prev) {
	    echo "<br><strong>$prev</strong><br>";
	    $chunksize = ceil(count($subjects)/$numcols);
	    $chunks = array_chunk($subjects, $chunksize);
	    foreach ($chunks as $list) {
		    echo "<div style='float:left; margin-left: 50px;'>";
		    echo join('<br>', $list);
		    echo "</div>\n";
	    }
	    echo "<div style='clear:both'></div>";
    }
    $subjects = array();
    $prev = $pupil;
   }
   $subjects[] = $subject;
}
// don't forget the last pupil
echo "<br><strong>$prev</strong><br>";
$chunksize = ceil(count($subjects)/$numcols);
$chunks = array_chunk($subjects, $chunksize);
foreach ($chunks as $list) {
   echo "<div style='float:left; margin-left: 50px;'>";
   echo join('<br>', $list);
   echo "</div>\n";
}


Link to comment
Share on other sites

Change

 

foreach ($chunks as $list) {
 echo "<div style='float:left; margin-left: 50px;'>";
 echo join('<br>', $list);
 echo "</div>\n";
}


 

to

 

echo "<table border='1'>\n";
foreach ($chunks[0] as $k=>$subj) {
echo "<tr>";
    echo "<td>$subj</td>";
    if (isset($chunks[1][$k])) {
        echo "<td>{$chunks[1][$k]}</td>";
    } else {
        echo "<td> </td>";
    }
echo "</tr>\n";
}
echo "</table>\n";

Edited by Barand
Link to comment
Share on other sites

Barand thanks again for your help.. I did it with some changes.. This is my actual code..

 

// Check SESSION fromm category page
if ( isset ( $_SESSION['category']) && is_array( $_SESSION['category'])) {

   $categoryIds = implode(',', $_SESSION['category']);

   $q = "SELECT  c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si
           FROM    category AS c
           INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id
           INNER JOIN subjects AS s ON s.subject_id = cs.subject_id
         WHERE   c.category_id IN ($categoryIds)";

   $r = mysqli_query( $dbc, $q) ;

   $numcols= 2;
   $lastCategory = FALSE;

   while (list($ci, $cn, $sn, $si) = $r->fetch_row()) {

       echo '<div>';   

       if ($ci != $lastCategory) {

           if ($lastCategory) {

               echo "<h3>Category 01: <span>$cn</span><span></span></h3>";
               echo "<div class='container'>\n";

               $chunksize = ceil(count($subjects)/$numcols);
               $chunks = array_chunk($subjects, $chunksize);

               echo "<table>\n";
               foreach ($chunks[0] as $k=>$subj) {
               echo "<tr>";
                        echo "<td width='50%'><input type='checkbox' value='1' name='subject[]' />$subj</td>";
                        if (isset($chunks[1][$k])) {
                                echo "<td width='50%'><input type='checkbox' value='1' name='subject[]' />{$chunks[1][$k]}</td>";
                        } else {
                                echo "<td width='50%'> </td>";
                        }
               echo "</tr>\n";
               }
               echo "</table>\n";
               echo "</div>\n";

           }

           $subjects = array();
           $lastCategory = $ci;
       }
       $subjects[] = $sn;

       echo '</div>';
   }
}

 

This script working.. But have a problem. assume 3 selected 3 category from my category page. then display only category with its subjects... If I choose 4 category then display 3 with its subjects... why is it happen?

Edited by thara
Link to comment
Share on other sites

This script working.. But have a problem. assume 3 selected 3 category from my category page. then display only category with its subjects... If I choose 4 category then display 3 with its subjects... why is it happen?

 

You have left out the foreach loop at the end of the script which outputs the final selected category.

Link to comment
Share on other sites

@Barand this is my updated code...

 

// Check SESSION fromm category page
if ( isset ( $_SESSION['category']) && is_array( $_SESSION['category'])) {

$categoryIds = implode(',', $_SESSION['category']);

$q = "SELECT c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si
FROM category AS c
INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id
INNER JOIN subjects AS s ON s.subject_id = cs.subject_id
WHERE c.category_id IN ($categoryIds)";

$r = mysqli_query( $dbc, $q) ;
$numcols= 2;
$lastCategory = FALSE;
echo '<div>';

while (list($ci, $cn, $sn, $si) = $r->fetch_row()) {

$value = "{$ci}:{$cn}:{$sn}:{$si}";

if ($ci != $lastCategory) {

if ($lastCategory != FALSE) {

echo "<h3>Category 01: <span>$cn</span><span></span></h3>";
echo "<div class='container'>\n";

$chunksize = ceil(count($subjects)/$numcols);
$chunks = array_chunk($subjects, $chunksize);

echo "<table>\n";
foreach ($chunks[0] as $k=>$subj) {
echo "<tr>";
 echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />$subj</td>";
 if (isset($chunks[1][$k])) {
 echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />{$chunks[1][$k]}</td>";
 } else {
 echo "<td width='50%'> </td>";
 }
echo "</tr>\n";
}
echo "</table>\n";
echo "</div> <!-- End .container DIV -->\n";
}

$subjects = array();
$lastCategory = $ci;
}
$subjects[] = $sn;


}

echo "<h3>Category 01: <span>$cn</span><span></span></h3>";
echo "<div class='container'>\n";

$chunksize = ceil(count($subjects)/$numcols);
$chunks = array_chunk($subjects, $chunksize);

echo "<table>\n";
foreach ($chunks[0] as $k=>$subj) {
echo "<tr>";
echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />$subj</td>";
if (isset($chunks[1][$k])) {
echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />{$chunks[1][$k]}</td>";
} else {
echo "<td width='50%'> </td>";
}
echo "</tr>\n";
}
echo "</table>\n";
echo "</div> <!-- End .container DIV -->\n";
echo '</div>';
}

 

Now Its working. When displaying category has a problem. Just think, I choose 3 categories with category ids 1,2,3. Above code start to display category name from ID 2 as first category and ID 3 as second category. In this case 3rd category name not display in this list.. If I select more categories than 3 the result is same. It start to display from second category_id. If I select one category then not display category name but display its subjects correctly.

 

In this image I have selected categories

01. Grade 1-4

02. Grade 5

03. Grade 6-10

 

But is start from Grade 5 category name. But display subjects which are belongs to category 1 in this case it is Grade 1-4

can you tell me where I am going wrong?

 

Thank you..

post-123452-0-51799600-1358131532_thumb.jpg

Link to comment
Share on other sites

Look at the code I originally posted.

 

It stores subjects in the array until there is a change of category (pupil). As these subjects belong to the previous category then you have to print lastCategory as the heading and not the new category as you are.

 

That is why the final foreach is required at the end so the final category is listed from the stored values.

Link to comment
Share on other sites

@Barand Thank you very much.. I got it clearly. But have a problem when Im going to pass category_id, category_name, subject_name and subject_id as the value of checkboxes. I got these values to one variable.. like this .

   while (list($ci, $cn, $sn, $si) = $r->fetch_row()) {

       if ($cn != $lastCategory) {

           if ($lastCategory == TRUE ) {

               echo '<h3>Category ' . sprintf("%02d ", $categoryNo) . ":<span> " . $lastCategory . "</span><span></span></h3>";
               echo "<div class='container'>\n";

               $chunksize = ceil(count($subjects)/$numcols);
               $chunks = array_chunk($subjects, $chunksize);

               echo "<table>\n";
               foreach ($chunks[0] as $k=>$subj) {
               echo "<tr>";
                   echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />$subj</td>";
                 if (isset($chunks[1][$k])) {
                   echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />{$chunks[1][$k]}</td>";
                 } else {
                   echo "<td width='50%'> </td>";
                        }
               echo "</tr>\n";
               }
               echo "</table>\n";
               echo "</div> <!-- End .container DIV -->\n";

           }            
           $subjects = array();
           $lastCategory = $cn;
           $categoryNo++;
       }        
       $subjects[] = $sn;
       $value = "{$ci}:{$cn}:{$sn}:{$si}";    
   }

 

Category_id and Category_name are ok. But subject_name and subject_id have problem. Same subject_id and subject_name printing within loop.

Can you tell my how can I fix this problem?

 

Thank you.

Link to comment
Share on other sites

@Barand, I tried something like this..

 

if ( isset ( $_SESSION['category']) && is_array( $_SESSION['category'])) {

$categoryIds = implode(',', $_SESSION['category']);

$q = "SELECT  c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si
  FROM    category AS c
  INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id
  INNER JOIN subjects AS s ON s.subject_id = cs.subject_id
   WHERE   c.category_id IN ($categoryIds)";

$r = mysqli_query( $dbc, $q) ;

echo '<div>';

$numcols= 2;
$lastCategory = FALSE;
$lastCatId = FALSE;
$categoryNo = 0;

while (list($ci, $cn, $sn, $si) = $r->fetch_row()) {

 if ( $cn != $lastCategory && $ci != $lastCatId ) {

  if ($lastCategory == TRUE &&  $lastCatId == TRUE) {

   echo '<h3>Category ' . sprintf("%02d ", $categoryNo) . ":<span> " . $lastCategory . "</span><span></span></h3>";
   echo "<div class='container'>\n";

   $chunksize = ceil(count($subjects)/$numcols);
   $chunks = array_chunk($subjects, $chunksize);

   echo "<table>\n";
   foreach ($chunks[0] as $k=>$subj) {
   echo "<tr>";
 echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />$subj</td>";
  if (isset($chunks[1][$k])) {
 echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />{$chunks[1][$k]}</td>";
  } else {
 echo "<td width='50%'> </td>";
   }
   echo "</tr>\n";
   }
   echo "</table>\n";
   echo "</div> <!-- End .container DIV -->\n";
  }
  $subjectsId = array();
  $subjects = array();
  $lastCategory = $cn;
  $lastCatId = $ci;
  $categoryNo++;
 }
 $subjectsId[] = $si;
 $subjects[] = $sn;
 $value = "{$lastCatId}:{$lastCategory}:{$sn}:{$si}";
}

echo '<h3>Category ' . sprintf("%02d ", $categoryNo) . ":<span> " . $lastCategory . "</span><span></span></h3>";
echo "<div class='container'>\n";

$chunksize = ceil(count($subjects)/$numcols);
$chunks = array_chunk($subjects, $chunksize);

echo "<table>\n";
foreach ($chunks[0] as $k=>$subj) {
 echo "<tr>";
  echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />$subj</td>";
   if (isset($chunks[1][$k])) {
  echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />{$chunks[1][$k]}</td>";
   } else {
  echo "<td width='50%'> </td>";
   }
  echo "</tr>\n";
}
echo "</table>\n";
echo "</div> <!-- End .container DIV -->\n";
echo '</div>';
}

 

But not sure how I use subjectsId array with loop. Tell me where I am going wrong...

 

Thank You.

Link to comment
Share on other sites

And also I would like to know How I detect how many checkboxes have selected from an user. (Subjects for one category.) I need to make at lease 1 subject must select to one category or upto 10 subjects for one category. It alse need to check when this dynamically generated form submit.?

 

any Ideas are highly appreciating.

Thank you.

Link to comment
Share on other sites

@Barand, can you explain this code little. Its pretty hard to understand and have a problem how I pass subject_id with it's subject withing foreach loop.

 

           	 echo "<table>\n";
               foreach ($chunks[0] as $k=>$subj) {
               echo "<tr>";
                   echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />$subj</td>";
                 if (isset($chunks[1][$k])) {
                   echo "<td width='50%'><input type='checkbox' value='$value' name='subject[]' />{$chunks[1][$k]}</td>";
                 } else {
                   echo "<td width='50%'> </td>";
                        }
               echo "</tr>\n";
               }
               echo "</table>\n";

 

Thank you..

Link to comment
Share on other sites

try this

 

$lastCategory = '';
$lastCatID = '';

while (list($ci, $cn, $sn, $si) = $r->fetch_row()) {

   echo '<div>';   

   if ($ci != $lastCatID) {

    if ($lastCatID) {

	    echo "<h3>Category 01: <span>$lastCategory</span><span></span></h3>";
	    echo "<div class='container'>\n";

	    $chunksize = ceil(count($subjects)/$numcols);
	    $chunks = array_chunk($subjects, $chunksize);

	    echo "<table>\n";
	    foreach ($chunks[0] as $k=>$subj) {
		    echo "<tr>";
		    $cbvalue = "$lastCatID:$lastCategory:{$subj['id']}:{$subj['nm']}";
		    echo "<td width='50%'><input type='checkbox' value='$cbvalue' name='subject[]' />{$subj['nm']}</td>";

		    if (isset($chunks[1][$k])) {
			    $subj = $chunks[1][$k];
			    $cbvalue = "$lastCatID:$lastCategory:{$subj['id']}:{$subj['nm']}";
			    echo "<td width='50%'><input type='checkbox' value='$cbvalue' name='subject[]' />{$subj['nm']}</td>";
		    } else {
			    echo "<td width='50%'> </td>";
		    }
		    echo "</tr>\n";
	    }
	    echo "</table>\n";
	    echo "</div>\n";

    }

    $subjects = array();
    $lastCategory = $cn;
    $lastCatID = $ci;
   }
   $subjects[] = array('id' => $si, 'nm' => $sn);

   echo '</div>';
}

echo "<h3>Category 01: <span>$lastCategory</span><span></span></h3>";
echo "<div class='container'>\n";

$chunksize = ceil(count($subjects)/$numcols);
$chunks = array_chunk($subjects, $chunksize);

echo "<table>\n";
foreach ($chunks[0] as $k=>$subj) {
   echo "<tr>";
   $cbvalue = "$lastCatID:$lastCategory:{$subj['id']}:{$subj['nm']}";
   echo "<td width='50%'><input type='checkbox' value='$cbvalue' name='subject[]' />{$subj['nm']}</td>";
   if (isset($chunks[1][$k])) {
    $subj = $chunks[1][$k];
    $cbvalue = "$lastCatID:$lastCategory:{$subj['id']}:{$subj['nm']}";
    echo "<td width='50%'><input type='checkbox' value='$cbvalue' name='subject[]' />{$subj['nm']}</td>";
   } else {
    echo "<td width='50%'> </td>";
   }
   echo "</tr>\n";
}
echo "</table>\n";
echo "</div>\n";

Edited by Barand
Link to comment
Share on other sites

Again I have a problem with this.. not this code. It is when I am trying to validate it... I have 3 conditions with this form submission and if those submission not found need to display 3 error messages..

 

There are my conditions.

 

1- select-subjectes array should not be empty

2- there is at least 3 subjects selected inside each category

3- all the selected categories' subjects should be checked and passed

 

I updated above code to suit for me.. this is my updated code..

 

$myCounter = 0;
    while (list( $ci, $cn, $si, $sn) = $r->fetch_row()) {	  


		    if ( $ci != $lastCatId ) {				     
				    if ($lastCatId == TRUE) {									  
						    echo '<h3>Category ' . sprintf("%02d ", $categoryNo) . ":<span> " . $lastCategory . "</span><span></span></h3>";
						    echo "<div class='container'>\n";
						    $myCounter = count($subjects); //assigning the number of categories
						    $chunksize = ceil(count($subjects)/$numcols);
						    $chunks = array_chunk($subjects, $chunksize);

						    echo "<table>\n";
						    foreach ($chunks[0] as $k=>$subj) {
						    echo "<tr>";

						    $cbvalue = "$lastCatId:{$subj['id']}";
								    echo "<td width='50%'><input type='checkbox' value='$cbvalue' name='select-subjectes[{$lastCatId}] []' />{$subj['nm']}</td>";

							  if (isset($chunks[1][$k])) {
								    $subj = $chunks[1][$k];
                                       $cbvalue = "$lastCatId:{$subj['id']}";

								    echo "<td width='50%'><input type='checkbox' value='$cbvalue' name='select-subjectes[{$lastCatId}] []' />{$subj['nm']}</td>";
							  } else {
								    echo "<td width='50%'> </td>";
											 }
						    echo "</tr>\n";
						    }
						    echo "</table>\n";
						    echo "</div> <!-- End .container DIV -->\n";

				    }	  
				    $subjects = array();
				    $lastCategory = $cn;
				    $lastCatId = $ci;
				    $categoryNo++;
		    }	  
		    $subjects[] = array('id' => $si, 'nm' => $sn);	     

		    //var_dump($ci);
    }

 

my problem is this going to validate. Meet 1st condition but not going to 1st and 2nd errors...

 

This is my validation script so far...

 

if ( isset($_POST['submitted_subjects'])) {


    if ( isset($_POST['select-subjectes']) && !empty( $_POST['select-subjectes'])) {

		    $counter = 0;

		    foreach ( $_POST['select-subjectes'] AS $category => $subjets) {
		    $counter++;
				    if ( (count($subjets)< 4) && (count($subjets)>=1 )) { //checking that it has 3 or more values.
							 //process
				    } else {
						    echo "select at leat 1 or upto 3 sports for {$category} ";		  
				    }  
		    }

		    if(isset($_POST['catcount'])) {
				    if((int)$_POST['catcount'] > $counter){
                           echo 'you have to select all the categories';
                       }
		    }

    } else {    
		    echo 'You have not selected sports for any country!';
    }	  
}

 

I passed $myCounter variable value as a hidden when form submitting...

 

<input type="hidden" name="catcount" value="<?php echo $myCounter; ?>" />

 

any answers are hightly appreciating...

 

Thank you..

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.