Getting bootstrap modal to display information from table rows - not working...

I have a page which is pulling fields from a database table to display information corresponding to rows. In my working example the rows represent teachers and  the fields relate to specific information relating to the teachers. To allow all the teachers in the database to be displayed, I use the following  php while loop:

 <?php while($teacher = mysqli_fetch_array($result)) //Goes through the results and carries out the following action while (for every) row in the result set
							 { ?> 

Open in new window


This works fine. However, I wanted to add a bootstrap modal to each of these rows. My issue is that the bootstrap modal is not displaying the fields associated with the specific teacher in the table - it seems to just display the information relating to the first teacher at the top of the table I am referencing.  

I've pasted my code below. Any ideas or suggestions to get the modal to display what's related to that row? Many thanks!

<div class="row">
                			  	   
				
							 <?php while($teacher = mysqli_fetch_array($result)) //Goes through the results and carries out the following action while (for every) row in the result set
							 { ?> 
																		
						 
						 
<!-- card--------------------------------------------------------------------------------------------------------->				
							 <div class="col-sm-6 col-md-4 buffer">
                    				<div class="card" style="width: 100%;">
        										<div class="card-header">
        										<img src="public/img/flags/<?php echo h ($teacher['nationality']) ?>flag.gif" alt="teacher nationality" />
                                                <a href = "<?php echo 'Profile.php?autonumber=' . $teacher['autonumber'];?>"><strong>&nbsp;&nbsp;&nbsp;<?php echo h($teacher['firstname']); ?></strong></a>&nbsp; - &nbsp;<?php echo h($teacher['language']); ?> teacher&nbsp;&nbsp;
												
                                                </div>
    									
                                          		<div class="card-body">
        											 <div align="center"> 
                									 <a href = "<?php echo 'Profile.php?autonumber=' . $teacher['autonumber'];?>"><img src="http://orangutanenglish.com/upload/<?php echo h($teacher['photoid']); ?>" class="ojborder " width="176" height="156" alt="" title="" /></a></div>
                        									  <div class="col-sm text-center">
                        									  <br />
                    									 	  	<?php
																if($teacher['teflconfirm'] == "yest")
																{print ("<IMG SRC =public/img/icons/yes_t_icon.gif>");}
																else  
																{print ("<IMG SRC =public/img/icons/no_t_icon.gif>");}
															   
																?>&nbsp;&nbsp;
                    											<?php
																if($teacher['degreeconfirm'] == "yesd")
																{print ("<IMG SRC =public/img/icons/yes_d_icon.gif>");}
																elseif ($teacher['degreeconfirm'] == "studying")  
																{print ("<IMG SRC =public/img/icons/studying_icon.gif>");}
																else  
																{print ("<IMG SRC =public/img/icons/no_d_icon.gif>");}
																?>&nbsp;&nbsp;
                    											<?php
																if($teacher['expconfirm'] == "expconfirm")
																{print ("<IMG SRC =public/img/icons/yes_exp_icon.gif>");}
																elseif ($teacher['expconfirm'] == "someexpconfirm")  
																{print ("<IMG SRC =public/img/icons/some_exp_icon.gif>");}
																else  
																{print ("<IMG SRC =public/img/icons/no_d_icon.gif>");}
																?>&nbsp;&nbsp;
                    									  		<?php
																if($teacher['vid'] == "1")
																{print ("<IMG SRC =public/img/icons/video1.gif>");}
																
																?>&nbsp;&nbsp;
																<br><br>
                                                                <h6 class="card-subtitle mb-2 text-muted"><div align="center">profile added: May 2017</div></h6>
                                                                <p class="card-text"><div align="center">Price per lesson: <?php echo h($teacher['private_price']); ?><br>Teaching Locations: <?php echo h($teacher['prefecture']); ?></div></p>
                                                       		  </div>
															
															
																<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
																  Launch demo modal
																</button>

																<!-- Modal -->
																<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
																  <div class="modal-dialog" role="document">
																	<div class="modal-content">
																	  <div class="modal-header">
																		<h5 class="modal-title" id="exampleModalLabel">A Message to <?php echo h($teacher['firstname']); ?></h5>
																		<button type="button" class="close" data-dismiss="modal" aria-label="Close">
																		  <span aria-hidden="true">&times;</span>
																		</button>
																	  </div>
																	  <div class="modal-body">
																		
																		<p><?php echo h($teacher['firstname']); ?> will receive the following email</p>
																		<br>
																		Hi  <?php echo h($teacher['firstname']); ?>
																		<br>
																		I saw your profile in OrangoJapan advertising <?php echo h($teacher['language']); ?>lessons and wanted to check your availability.
																		<br>
																		If you are still available to teach can you mail me back? 
																		<br>
																		Please confirm the details on your profile are up to date.
																		<br>
																		Your current profile says your price per hour is {price} and your free first lesson status is {status}
																		
																		Please note - this is an automated message from OJ after a student expressed interest in your profile for a lesson. 
																		
																		Thanks
																	  </div>
																	  <div class="modal-footer">
																		<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
																		<button type="button" class="btn btn-primary">Email Teacher!</button>
																	  </div>
																	</div>
																  </div>
																</div>
																<!-- Modal -->
													</div>
                                        	  
											 check <?php echo h($teacher['firstname']); ?>
                    				
                				  </div>
							</div>	
					 
					  <?php } ?> 
					 
<!-- card-------------------------------------------------------------------------------------------------------------> 				 
			
			

	
	</div>

Open in new window

AdamTrying to learn phpAsked:
Who is Participating?
 
NerdsOfTechTechnology ScientistCommented:
Thank you for the extra information

It looks like your PHP is looping through the data correctly, however, the HTML Entities with the same ID i.e. ="exampleModal" are currently colliding; therefore, the data which is currently being pulled up for all modals, is the data from the first ID.

To correct this you can dynamically load data in as Scott suggests; or, alternatively use an increment variable to dynamically populate unique IDs (shown in the code below). Since key() function may have unexpected results in while(), I opted for a simple $i variable for the counter.

<div class="row">


<?php 
$i = 0; // sequence number to identify modal id
while($teacher = mysqli_fetch_array($result)){ 
	//Goes through the results and carries out the following action while (for every) row in the result set
?>  

<!--// card start //-->				
<div class="col-sm-6 col-md-4 buffer">
	<div class="card" style="width: 100%;">
		<div class="card-header">
			<img src="public/img/flags/<?php echo h ($teacher['nationality']) ?>flag.gif" alt="teacher nationality" />
			<a href = "<?php echo 'Profile.php?autonumber=' . $teacher['autonumber'];?>"><strong>&nbsp;&nbsp;&nbsp;<?php echo h($teacher['firstname']); ?></strong></a>&nbsp; - &nbsp;<?php echo h($teacher['language']); ?> teacher&nbsp;&nbsp;
		</div>
		<div class="card-body">
			<div align="center"> 
				<a href = "<?php echo 'Profile.php?autonumber=' . $teacher['autonumber'];?>"><img src="http://orangutanenglish.com/upload/<?php echo h($teacher['photoid']); ?>" class="ojborder " width="176" height="156" alt="" title="" /></a>
			</div>
			<div class="col-sm text-center">
				<br />
<?php
if($teacher['teflconfirm'] == "yest"){
	echo "<IMG SRC =public/img/icons/yes_t_icon.gif>";
}else{
	echo "<IMG SRC =public/img/icons/no_t_icon.gif>";
}
?>			&nbsp;&nbsp;

<?php
if($teacher['degreeconfirm'] == "yesd"){
	echo "<IMG SRC =public/img/icons/yes_d_icon.gif>";
}elseif ($teacher['degreeconfirm'] == "studying"){
	echo "<IMG SRC =public/img/icons/studying_icon.gif>";
}else{
	echo "<IMG SRC =public/img/icons/no_d_icon.gif>";
}
?>			&nbsp;&nbsp;

<?php
if($teacher['expconfirm'] == "expconfirm"){
	echo "<IMG SRC =public/img/icons/yes_exp_icon.gif>";
}elseif ($teacher['expconfirm'] == "someexpconfirm"){
	echo "<IMG SRC =public/img/icons/some_exp_icon.gif>";
}else{
	echo "<IMG SRC =public/img/icons/no_d_icon.gif>";
}
?>			&nbsp;&nbsp;

<?php
if($teacher['vid'] == "1"){
	echo "<IMG SRC =public/img/icons/video1.gif>";
}
?>			&nbsp;&nbsp;

				<br><br>
				<h6 class="card-subtitle mb-2 text-muted"><div align="center">profile added: May 2017</div></h6>
				<p class="card-text"><div align="center">Price per lesson: <?php echo h($teacher['private_price']); ?><br>Teaching Locations: <?php echo h($teacher['prefecture']); ?></div></p>
			</div>

				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal-<?php echo $i?>">
				Launch demo modal
				</button>

				<!--// Modal start //-->
				<div class="modal fade" id="exampleModal-<?php echo $i?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-<?php echo $i?>" aria-hidden="true">
					<div class="modal-dialog" role="document">
						<div class="modal-content">
							<div class="modal-header">
								<h5 class="modal-title" id="exampleModalLabel-<?php echo $i?>">A Message to <?php echo h($teacher['firstname']); ?></h5>
								<button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
							</div>
							<div class="modal-body">
								<p><?php echo h($teacher['firstname']); ?> will receive the following email</p>
								<br>
								Hi  <?php echo h($teacher['firstname']); ?>
								<br>
								I saw your profile in OrangoJapan advertising <?php echo h($teacher['language']); ?>lessons and wanted to check your availability.
								<br>
								If you are still available to teach can you mail me back? 
								<br>
								Please confirm the details on your profile are up to date.
								<br>
								Your current profile says your price per hour is {price} and your free first lesson status is {status}

								Please note - this is an automated message from OJ after a student expressed interest in your profile for a lesson. 

								Thanks
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="button" class="btn btn-primary">Email Teacher!</button>
							</div>
						</div>
					</div>
				</div>
				<!-- Modal end //-->
			</div>

			check <?php echo h($teacher['firstname']); ?>

		</div>
	</div>	
	<!--// card end //-->
<?php 
$i++;	// increment sequence number
} 
?> 
</div>

Open in new window


cleaned up a few things: changed print() to echo, fixed tabbing (I hope it renders here ok), shortened the html comment codes
0
 
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
The best approach is to create a php page that will generate your data separate from this page.  Then run an ajax call to the php page that returns the result and inject it to the modal.

See if my old answer here gets you in the right direction.  I would stay away from trying to inject the data right on the page.

https://www.experts-exchange.com/questions/28944397/Could-you-point-how-to-obtain-a-variable-defined-from-inside-a-bootstrap-modal-screen-with-a-php-code-running-inside.html#a41583447
2
 
NerdsOfTechTechnology ScientistCommented:
Performance: use mysqli_fetch_assoc instead of mysqli_fetch_array to shave off a few milliseconds.

What's function h() do?

try debugging $result before the while line:

<pre>
<?php print_r($result); ?>
</pre>

Open in new window


Does the $result output look correct? If not, it might be your SQL statement that is the issue.
0
Network Scalability - Handle Complex Environments

Monitor your entire network from a single platform. Free 30 Day Trial Now!

 
AdamTrying to learn phpAuthor Commented:
Thanks Scott, Nerds of Tech, and apologies for the delay in replying.

The h() function is one I picked up from another tutorial -  I understand it is for abbreviating html special characters to make sure no characters can be input dynamically.

function h($string="") { return htmlspecialchars($string); }

The result of the while loop works outside the model, but just not inside the model, which is created in the while loop. The screenshot (below) shows the while loop working but the modal displaying information relating to the first person in the database.

Scott - I'm not sure I understood exactly what you meant in your comment.  Do you mean I should have a while loop within the modal? I'm  not really familiar with ajax so if I could perform in php that would probably be easier for me.

Many thanks.

Screen shot showing while loop in effect pulling fields from each row...

screenshot showing working while
However, this screenshot shows that even when the modal button for the second person on the DB (Noemi) is selected, the model still shows information relating to the first person (Rolyanda)

Screenshot showing modal not displaying expected while content
0
 
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
>  I'm not sure I understood exactly what you meant in your comment.

You have to think of the server side (php) and client side (jquery/js) as separate functions.  Serverside php runs on the server and interacts with the database before anything is pushed to the browser. Once all data is extracted and any calculations you have set up runs, the server pushes data to the browser. At that point, javascript/jquery takes over and never directly interacts with php or your database.

Let's start by looking just at the client side of things and the steps are below.
  1. Gather Data
  2. Build response to show inside the modal
  3. Inject the response data to the modal
  4. Show the modal

It is at step 1 where you add your php code as demonstrated to populate a js variable that will eventually go to your modal.  If it is a one off, then the example works as is. If the page is set up to be interactive where things can change on the fly, then you will want to make an ajax call to another php that will push out data depending on the input.

http://jsbin.com/dovijixuzo/edit?html,output
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
  <script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
  
$(function() {

    //STEP 1: GATHER DATA
    // ASSUME THIS IS DATA FROM OUR PHP CALL
  /*
            Below is where you can use php to populate a js variable.
            An easy option would be outputting php data to json, then
            set a js variable 
            var array = <?php echo data; ?>
            If this data needs to change based on user input, then
            using an ajax call to another php will be the best option.
         */


    var item1 = 'item-1';
    var item2 = 'item-2';
    var item3 = 'item-3';


    $('#doModal').on('click', function() {

        // STEP 2: BUILD DATA TO INJECT TO MODAL
       

        var modalData = '<ul>';
        modalData += '<li>' + item1 + '</li>';
        modalData += '<li>' + item2 + '</li>';
        modalData += '<li>' + item3 + '</li>';
        modalData += '</ul>';

        // STEP 3: INJECT DATA TO <div class="modal-body">

        $('.modal-body').html(modalData);

        // STEP 4: OPEN MODAL
        $('#myModal').modal('show');


    });

});
  
</script>
  
  
</head>
<body>
  <div id="content">
    <button id="doModal">Open Modal</button>
    
    
  </div>
  <!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <!-- INJECT MODAL CONTENT HERE -->
        <!-- NOTE THAT MODAL STARTS WITHOUT ANY DATA -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</body>
</html>

Open in new window


The key is to get your php variables set to a js variable and let js/jquery/bootstrap take it from there.
2
 
AdamTrying to learn phpAuthor Commented:
Hi Scott, NerdsOfTech,

Many thanks both of you for your help. It's always good to learn two ways of doing something.

Scott - thanks for the detailed explanation. I guess as I try to develop I'll need to start becoming familiar with javascripts / jquerys and get a better understanding of client and server side programming.

NerdsofTech - I've looked to implement your suggestion as for me, it seems less removed from what I already had and slightly easier for my small brain to grasp.  I used your suggested code and it works as hoped. Fantastic! I also appreciate the cleaning up and improving of my code.

Again, many thanks both. Have a great rest of the week.
1
 
AdamTrying to learn phpAuthor Commented:
Sorry Scott Fell - I meant to award some points for an assisted solution there, but seemed to have messed that up. Thanks.
1
 
NerdsOfTechTechnology ScientistCommented:
I'm asking to modify for split points.
1
 
AdamTrying to learn phpAuthor Commented:
Hi Moderato.

I can't see an option to split points here. I only see a Best Solution button. And I can only select one Best solution (normally the set up appears different - and it's straight-forward to split points?)  I'm going to press the Finish button to see if I can then get the option to split points. If it doesn't work again, can you split 60-40 between NerdsofTech(60) and Scott(40) or re-open and tell me how to split the points.

Many thanks.
0
 
AdamTrying to learn phpAuthor Commented:
Yup, this same things happened again. I'll contact the moderators directly to try to resolve.

Thanks.
0
 
AdamTrying to learn phpAuthor Commented:
I've raised a request with the moderator to split these points, and explain why I wasn't seeing the option to share points.

Thanks all.
0
 
NerdsOfTechTechnology ScientistCommented:
I just realized that experts-exchange recently changed how point splitting works:

you have to mark solutions that you want to include in the "assisted" solution "helpful" first... I sort of like to old method as it was less confusing.

http://support.experts-exchange.com/customer/portal/articles/2527982-how-do-i-close-my-question-

Hope this helps.
0
 
AdamTrying to learn phpAuthor Commented:
Okay - third time's hopefully a charm. I've marked a post from Scott and NerdsofTech as helpful and the NerdsofTech comment as the best solution. I've had no option with respect to how I split the points yet. I'll press 'Finish' and see what happens...
0
 
AdamTrying to learn phpAuthor Commented:
So I see the points have been halved.  So I guess this means any helpful answers get an equal share of the points regardless of how 'helpful' they are.  I also preferred the older method - seemed fairer, and less confusing. Thanks all for the patience in getting this sorted.
2
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.