Call Bootstrap Modal within PHP If statement

I have a form to mark attendance of people for a convention. The problem is I need to summon this modal:

<div class="modal fade" id="checkModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-backdrop="static">
				<div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Import Troubleshooting</h5>
							<button class="close" type="button" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">Ɨ</span>
							</button>
						</div>
						<div class="modal-body">
							<p>An absence record already exists for this delegate. Do you want to convert this record?</p>
						</div>
						<div class="modal-footer">
              <button class="btn btn-secondary" type="button" data-dismiss="modal">No</button>
              <a class="btn btn-danger" href="convert.php">Yes</a>
						</div>
					</div>
				</div>
			</div>

within this IF statement in PHP:

if(isset($_POST['btn_save'])) {
  // Check to see if delegate exists in the Absence table
  $fsQuery = $pdo->prepare("SELECT COUNT(*) AS num FROM absence WHERE member_id = :member_id");
  $fsQuery->bindParam(':member_id', $member_id);
  $id = $_POST["member_id"];
  $ary = explode("-", $id);
  $member_id = $ary[0];
  $fsQuery->execute();
  $check = $fsQuery->fetch(PDO::FETCH_ASSOC);

  if($check['num'] > 0) {
    // CALL MODAL HERE

I canā€™t figure this out and it is driving me crazy. What do I do?

It can be called with jquery by simply echoing some js after jquery is called to the page. I tend to do all form processing before page is rendered to the browser. In general I also would have jquery at the bottom of the page. So in my case I would set a unique variable based on your processing conditions, e.g.

if($check['num'] > 0) {
	$showModal = "true";		 
}

Then at the bottom of the page after jquery is called add a php IF condition to echo the js.

<script src="assets/js/jquery.js"></script>
<?php			
	if(!empty($showModal)) {
		// CALL MODAL HERE
		echo '<script type="text/javascript">
			$(document).ready(function(){
				$("#checkModal").modal("show");
			});
		</script>';
	} 
?>

This worked! Thank you very much!

Another question I just thought of. I have two buttons in the modal since it is gonna be used as a confirm modal. So if someone clicks Yes, I need to run another action whereas if they click no, an error appears.

Can I run this through a standard PHP query or do I need to run this through JS?

The modal should have its own <form> tag to call an action and so like you did the first form check which buttons are being passed by the form and process accordingly. i.e. ā€œnew actionā€ or ā€œshow errorā€

I modified the modal footer to show the following:

<div class="modal-footer">
     <input type="submit" name="btn_stop" class="btn btn-secondary" value="No">
     <input type="submit" name="btn_convert" class="btn btn-danger" value="Yes">
</div>

Now I need to add the condition where if Yes is clicked, the action needs to take place and when No is clicked, an error appears.

Iā€™ve tried this, but it didnā€™t work:

if(isset($_POST['btn_convert'])) { // if "Yes" is clicked...
      $delQuery = $pdo->prepare("DELETE FROM absence WHERE member_id = :member_id");
      $delQuery->bindParam(':member_id', $member_id);
      $id = $_POST["member_id"];
      $ary = explode("-", $id);
      $member_id = $ary[0];
      $delQuery->execute();
      $stmt->execute();
    } elseif(isset($_POST['btn_stop'])) { // if "No" is clicked...
      $msg = "There has been an error processing your request.";
  }

Basically, what Iā€™m trying to do is: if Yes is clicked, I need to move a record from one table in my database to another (this may or may not be coded right in my if statementā€¦). If No is clicked, the page reloads and an error shows up saying ā€œThere has been an error processing your request.ā€

if($check['num'] > 0) {
    $showModal = "true";
// if statement here
  }

Can I process this on the same page as the modal or do I need to make a new page?

It is a little unclear how this is being used as you say you are marking attendance for many people. Is the modal part of a larger form? In a loop? Stand alone?
I am not seeing form tags i.e. <form action="" method="post"></form> or see how the member_id is being passed. The form action can point to the same page no problem but I would do it above any output to the browser. If each record is passing the member_id when you click 'btn_save' then you need to pass any needed values, .e.g. member_id to hidden inputs in your modal so the modal itself is its own form with stop - convert buttons.
I am not saying to nest form tags if you are building this in some loop of records within a larger form. In fact if you are building the modal within a loop then thatā€™s going to be a problem as each would have the same button name. The modal should be a stand alone that has values passed to it and opened.

So here is the full PHP code (this does not include the modal code in the footer):

include('nav/head.php');

$msg = "";

// Prepare SQL Statement
$stmt = $pdo->prepare("INSERT INTO attendance (member_id, member_email, member_phone, present, attend_state) VALUES (:member_id, :member_email, :member_phone, :present, :attend_state)");
$stmt->bindParam(':member_id', $member_id);
$stmt->bindParam(':member_email', $member_email);
$stmt->bindParam(':member_phone', $member_phone);
$stmt->bindParam(':present', $present);
$stmt->bindParam(':attend_state', $attend_state);

// insert a row and add new record
if(isset($_POST['btn_save'])) {
  // Check to see if delegate exists in the Absence table
  $fsQuery = $pdo->prepare("SELECT COUNT(*) AS num FROM absence WHERE member_id = :member_id");
  $fsQuery->bindParam(':member_id', $member_id);
  $id = $_POST["member_id"];
  $ary = explode("-", $id);
  $member_id = $ary[0];
  $fsQuery->execute();
  $check = $fsQuery->fetch(PDO::FETCH_ASSOC);

  if($check['num'] > 0) {
    $showModal = "true";
  } else {
    try {
      $id = $_POST["member_id"];
      $ary = explode("-", $id);
      $member_id = $ary[0];
      $member_email = $_POST["member_email"];
      $member_phone = $_POST["member_phone"];
      $present = $_POST["present"];
      $attend_state = $_POST["attend_state"];
      $stmt->execute();
      header('Location: record_attn.php');
      exit();
    } catch(PDOException $e) {
        $msg = "This delegate has already been marked present";
      }
    }
  }

So the process is when btn_save is clicked, it checks to see if there is an absence record for that person since in-person attendance will take precedence over an absence. If there isnā€™t any, it will mark that person present if they havenā€™t been marked as present already. If it finds one, it will stop and the modal pops up asking if they wish to remove the absent record and mark the person present (what I call ā€œconvertingā€ the record).

My question is I need to build a condition where if btn_convert is clicked, it will remove the absence record and add the attendance record whereas if btn_stop is clicked, the $msg populates with ā€œThere has been an error processing your request.ā€ and the page reloads.

The previous if statement that I wrote earlier is what I think I need to do, but I canā€™t figure out why it isnā€™t working.

The original attendance form looks like this:

<form action="record_attn.php" method="post" id="record">
		<div class="form-group search-box">
			<label for="member_id">Member Search</label>
			<input type="text" class="form-control" id="member_id" name="member_id" placeholder="Enter Member's Last Name" maxlength="" autocomplete="off" autofocus="autofocus" required />
			<div class="result"></div>
		</div>
		<!--<div class="form-group">
			<label for="member_id">Member ID</label>
			<input type="text" class="form-control" id="member_id" name="member_id" placeholder="" maxlength="255" autocomplete="off" readonly/>
		</div>-->
    <div class="form-group">
			<label for="member_email">Member's Email Address</label>
			<input type="email" class="form-control" id="member_email" name="member_email" placeholder="" maxlength="255" autocomplete="off" />
		</div>
		<div class="form-group">
			<label for="member_phone">Member's Phone Number</label>
			<input type="tel" class="form-control" id="member_phone" name="member_phone" placeholder="(123) 456-7890" maxlength="14" autocomplete="off" onkeyup="maskPhoneNo();" />
		</div>
		<div class="form-group">
			<label for="present">Attended &nbsp</label>
			<input type="checkbox" id="present" name="present" placeholder="" value="1" autocomplete="off" required />
		</div>
		<div class="form-group">
			<label for="attend_state">Plan to Attend State Convention? &nbsp</label>
      <input type="hidden" id="attend_state" name="attend_state" placeholder="" value="0" autocomplete="off" checked/>
      <input type="checkbox" id="attend_state" name="attend_state" placeholder="" value="1" autocomplete="off" checked/>
		</div>
			<input type="submit" name="btn_save" class="btn btn-success" value="Save and Add New">
			<!--<input type="submit" name="btn_close" class="btn btn-danger" value="Save and Close">-->
      <a class="btn btn-danger" href="index.php">Return Home</a>
	</form>

So the modal needs its own form tags and hidden inputs to hold member_id and other needed values from the first form or processing information from the query you did.

This is what adds the record and marks it present. So I need to add this query to the modal?

$stmt = $pdo->prepare("INSERT INTO attendance (member_id, member_email, member_phone, 
present, attend_state) VALUES (:member_id, :member_email, :member_phone, :present, 
:attend_state)");
$stmt->bindParam(':member_id', $member_id);
$stmt->bindParam(':member_email', $member_email);
$stmt->bindParam(':member_phone', $member_phone);
$stmt->bindParam(':present', $present);
$stmt->bindParam(':attend_state', $attend_state);
<div class="modal-body">
       <p>An absence record already exists for this delegate. Do you want to convert this record?</p>
</div>
<div class="modal-footer">
      <form action="" method="post">
          <input type="submit" name="btn_stop" class="btn btn-secondary" value="No">
           <input type="submit" name="btn_convert" class="btn btn-success" value="Yes">
      </form>

How would you use a hidden input and keep its value? Something like this?

<input type="email" 
class="form-control" 
id="member_email" 
name="member_email" 
placeholder="" 
maxlength="255" 
value="<?php $_POST['member_email']; ?>" 
autocomplete="off" />

Sure add all the values needed into hidden inputs. Note you donā€™t need class attributes etc on these hidden inputs. I wouldnā€™t use $_POST directly as that is not always present. Set a condition variable that you can echo as the value. Something like this.

<?php
$member_id = (!empty($_POST['member_id']) ? $_POST['member_id'] : '');
$member_email = (!empty($_POST['member_email']) ? $_POST['member_email'] : '');
$member_phone = (!empty($_POST['member_phone']) ? $_POST['member_phone'] : '');
?>						
<form action="" method="post">
	<input type="hidden" name="member_id" value="<?php echo $member_id; ?>" />
	<input type="hidden" name="member_email" value="<?php echo $member_email; ?>" />
	<input type="hidden" name="member_phone" value="<?php echo $member_phone; ?>" />
	<input type="hidden" name="attend_state" value="1" />
	<input type="submit" name="btn_stop" class="btn btn-secondary" value="No">
	<input type="submit" name="btn_convert" class="btn btn-success" value="Yes">
</form>

EDIT attendance processing wants the member_phone as well so add that as a hidden input.
Then just make 2 different processing conditions for your buttons.

if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['btn_convert'])):
	//Attendance Processing
endif; 
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['btn_stop'])): 
	//Define message
endif; 

Might I suggest that you write your ā€œmessageā€ a little different as there wasnā€™t a ā€œProblemā€ with coding or anything. The user just changed his mind and clicked ā€œNoā€. A more appropriate message might be ā€œNo Changes Were Madeā€ā€¦ Just a thought.

Iā€™m curious about the member_id part.

So the member_id is actually an array of a search result that is selected from a search box. So if I put $_POST['member_id] the record Iā€™m adding might be something like:

12345 - SMITH, JOHN A | (01-14) | 123 Exmaple St. City, State ZIP

So if I do $_POST['member_id'] that is what will come out. The member id itself is this:

12345

So $_POST['member_id'] is actually split in an array and the following code produces the correct result that I need.

$id = $_POST["member_id"];
  $ary = explode("-", $id);
  $member_id = $ary[0];

How can I be sure I am only grabbing the member id number when I use the code you mentioned above?

Also, email and phone arenā€™t required in the code. Does that make a difference as to what you wrote? I donā€™t think it does, but I just want to be sure.

Sorry for late reply.
My bad, I thought we were passing info from the main attendance form, which looked pretty straight forward.
I agree you shouldnā€™t need any other value passed but the member_id so I would pull that out and pass it to the modal form. Something like this.

<?php														 
$member_id = (!empty($_POST['member_id']) ? explode("-", $_POST['member_id']) : '');
$member_id = (!empty($member_id) ? trim(reset($member_id)) : '');
?>						
<form action="" method="post">
	<input type="hidden" name="member_id" value="<?php echo $member_id; ?>" />
	<input type="submit" name="btn_stop" class="btn btn-secondary" value="No">
	<input type="submit" name="btn_convert" class="btn btn-success" value="Yes">
</form>

I managed to get this far:

<?php
$member_id = (!empty($_POST['member_id']) ? explode("-", $_POST['member_id']) : '');
$member_id = (!empty($member_id) ? trim(reset($member_id)) : '');
$member_email = (!empty($_POST['member_email']) ? $_POST['member_email'] : '');
$member_phone = (!empty($_POST['member_phone']) ? $_POST['member_phone'] : '');
$present = (!empty($_POST['present']) ? $_POST['present'] : '');
$attend_state = (!empty($_POST['attend_state']) ? $_POST['attend_state'] : '');
?>
<form action="" method="post">
      <input type="hidden" name="member_id" value="<?php echo $member_id; ?>" />
      <input type="hidden" name="member_email" value="<?php echo $member_email; ?>" />
      <input type="hidden" name="member_phone" value="<?php echo $member_phone; ?>" />
      <input type="hidden" name="present" value="<?php echo $present; ?>" />
      <input type="hidden" name="attend_state" value="<?php echo $attend_state; ?>" />
      <input type="submit" name="btn_stop" class="btn btn-secondary" value="No">
      <input type="submit" name="btn_convert" class="btn btn-success" value="Yes">
</form>
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['btn_convert'])):
        $delQuery = $pdo->prepare("DELETE FROM absence WHERE member_id = :member_id");
        $delQuery->bindParam(':member_id', $member_id);
        $id = $_POST["member_id"];
        $ary = explode("-", $id);
        $member_id = $ary[0];
        $delQuery->execute();
      endif;
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['btn_stop'])):
      	$msg = "This delegate could not be marked present. Please try again.";
      endif;

Now, when I add stmt->execute(); to the if statement, I am met with this error:

Fatal error : Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: ā€˜ā€™ for column cabgop_db.attendance.attend_state at row 1 in /var/www/cabgop/record_attn.php:182 Stack trace: #0 /var/www/cabgop/record_attn.php(182): PDOStatement->execute() #1 {main} thrown in /var/www/cabgop/record_attn.php on line 182

Also, if "No: is clicked, no error message appearsā€¦

This is kind of why I dislike this logic. Thereā€™s a lot of unnecessary stuff when it comes to logic that operate like this. You should stop relying on which button is clicked, but rather pass in a URL that accepts a delete operation. I know youā€™re kind of far into this already, but what I would do is rewrite the HTML and logic.

Instead of having hidden input fields that are really unnecessary, I would just get the memberā€™s ID from the URL. From there, I would do a SELECT statement that selects that particular member. Once I do that, I already have information about the user. I donā€™t need to pass any of that information in since they should have that information provided when they sign up. The only thing you would be asking for is a passcode or something for that specific class session. The other rest of the information would be trivial to retrieve.

So this:

if(isset($_POST['btn_save'])) {
  // Check to see if delegate exists in the Absence table
  $fsQuery = $pdo->prepare("SELECT COUNT(*) AS num FROM absence WHERE member_id = :member_id");
  $fsQuery->bindParam(':member_id', $member_id);
  $id = $_POST["member_id"];
  $ary = explode("-", $id);
  $member_id = $ary[0];
  $fsQuery->execute();
  $check = $fsQuery->fetch(PDO::FETCH_ASSOC);

  if($check['num'] > 0) {
    $showModal = "true";
  } else {
    try {
      $id = $_POST["member_id"];
      $ary = explode("-", $id);
      $member_id = $ary[0];
      $member_email = $_POST["member_email"];
      $member_phone = $_POST["member_phone"];
      $present = $_POST["present"];
      $attend_state = $_POST["attend_state"];
      $stmt->execute();
      header('Location: record_attn.php');
      exit();
    } catch(PDOException $e) {
        $msg = "This delegate has already been marked present";
      }
    }
  }

is wrong?

I am not seeing my reply, which I submitted earlier so I am submitting again.

Hey this is your baby and you are in the driverā€™s seat. You should know better than anyone how this is being used and under what circumstances things are happening.

If it were me, at the top of the page I would have the members data in an array the moment they are selected or searched for. Then no matter how you need their data youā€™ve got it. Want to fill out that registration form to edit something, bam you got all their info. Need to change their status or add their information to another table, youā€™ve got it. I can understand having an autocomplete search input that can search for member ID, first and last or address but I would not pass that search result into an input called member_id. I wouldnā€™t use that past the initial search of finding the member. After that you should have their data and say ā€œnow what do I need to do with it?ā€ If there is a bunch of back and forth between displays where youā€™re dealing with this member you might consider saving it to session so as long as you are in ā€œEdit Modeā€ their info is available. When done unset that session.

Often projects will have a list of items, letā€™s say 1000 items and you realistically can only show for example 50 items so you will use pagination and query just this set of records. But if you built a data array with your query result at the top of the page instead of just echoing in the display section, this data is available no matter how it is needed. To make it accessible, build the array with the id as the primary key for example,


$data[$row[id']] = $row;

For that ā€œlist viewā€ you just use foreach to loop through the data and then just call a record by its ID and all data fields are available. For example,


$item = "4578";

$data[$item]['name'];

As long as you are working with this record youā€™ll pass the ID alone the different forms but data comes from the array.

ANYWAY this is your baby. Information needed and information available will determine what is missing. We were talking about a modal popup with a form and passing required info.or having required info available when processing etc.

I suppose a bigger question is why even this approach?

A simple query change by adding LEFT JOIN to the absent or attendance table (however works for you) would make that information known in the list of members so their attendance status is shown to the user before any button is pressed. There would be this ā€œMark as Absentā€- WHOPS they are already marked as absent.

Again, just a thought. It is better to write a smart program than figure out as many ways to frustrate the use by saying ā€œThere was an errorā€ because ā€œI am making the correct choice of canceling my request to mark as absent because they are already marked as absentā€¦ā€ Oh how frustrating that I didnā€™t remember out of these 100s of records. ā€œBut it didnā€™t tell me!ā€ ---- Iā€™m telling you now error, error!

///

Just now seeing your query error.

If in the modal popup form you have already broken the actual member_id out of the first post with.

$member_id = (!empty($_POST['member_id']) ? explode("-", $_POST['member_id']) : '');

$member_id = (!empty($member_id) ? trim(reset($member_id)) : '');

Then in the popup processing $_POST[ā€˜member_idā€™] IS the actual member_id instead of the string of dataā€¦

1 Like

The following error appears when I remove this line:

$member_id = (!empty($member_id) ? trim(reset($member_id)) : '');

Notice : Array to string conversion in /var/www/cabgop/record_attn.php on line 177

Fatal error : Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: ā€˜ā€™ for column cabgop_db.attendance.attend_state at row 1 in /var/www/cabgop/record_attn.php:182 Stack trace: #0 /var/www/cabgop/record_attn.php(182): PDOStatement->execute() #1 {main} thrown in /var/www/cabgop/record_attn.php on line 182

All Iā€™m trying to do is make a popup box that basically says Hey, I see you have a person here, but I already have this guy marked down as absent. Do you want to convert this record and have me mark them as attended instead? with a Yes or No. I already did this when you showed me how to trigger the modal using JS.

Now Iā€™m looking at PHP. If I click Yes, the entire absence record that already exists needs to be deleted because the data is in another table. At the same time, the information I entered in the attendance form needs to be submitted into a second table to make the correction.

Using PHP, I have already defined the query that needs to be processed:

$stmt = $pdo->prepare("INSERT INTO attendance (member_id, member_email, 
member_phone, present, attend_state) VALUES (:member_id, :member_email, 
:member_phone, :present, :attend_state)");
$stmt->bindParam(':member_id', $member_id);
$stmt->bindParam(':member_email', $member_email);
$stmt->bindParam(':member_phone', $member_phone);
$stmt->bindParam(':present', $present);
$stmt->bindParam(':attend_state', $attend_state);

The data I need is already stored in these variables because the query is called later when a record goes through without issue unless that person has already been marked present in which case the system will stop and prompt me saying This delegate has already been marked present.

try {
      $id = $_POST["member_id"];
      $ary = explode("-", $id);
      $member_id = $ary[0];
      $member_email = $_POST["member_email"];
      $member_phone = $_POST["member_phone"];
      $present = $_POST["present"];
      $attend_state = $_POST["attend_state"];
      $stmt->execute();
      header('Location: record_attn.php');
      exit();
    } catch(PDOException $e) {
        $msg = "This delegate has already been marked present";
      }

I donā€™t think I need to identify the query a second time in the modal since that would be too redundant. So I want to call the original query I defined after the check goes through by running $stmt->execute();. The problem is the query stops when it hits the checkboxes and Iā€™m not sure why.

The other side of the coin is if I click No, the page needs to reload and a message appears saying This person could not be marked present. Please try again.

To set the message, I define the message (or error) variable at the top of the page (or code) like this:

$msg = "";

Then, I create a place in HTML for the error to be shown like this:

<div class="small">
   <p style="text-align: left; font-size: 14px;"><b class="text-danger"><?php echo $msg; ?></b></p>
</div>

If the code fails, messages (or errors) are automatically generated. This one, for instance, where a duplicate record is entered:

} catch(PDOException $e) {
        $msg = "This delegate has already been marked present";
      }

If a duplicate record is entered, the page will reload itself and that message shows up in red at the top of the page. I need this exact same thing to happen when I click ā€œNoā€ in my modal. The page should reload first, then the message should appear. But this time, no message shows up?

if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['btn_stop'])):
   $msg = "This delegate could not be marked present. Please try again.";
endif;

You are right. This program is my baby and I know exactly what I need to code in order to make it work. What I struggle with is how to code it.

You need both these lines otherwise you are passing an array as the value.

Okay, but that doesnā€™t explain this:

Fatal error : Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: ā€˜ā€™ for column cabgop_db . attendance . attend_state at row 1 in /var/www/cabgop/record_attn.php:182 Stack trace: #0 /var/www/cabgop/record_attn.php(182): PDOStatement->execute() #1 {main} thrown in /var/www/cabgop/record_attn.php on line 182

Please test what is being posted before attempting to shove it into your database. Make sure are values are as expected.

echo "<pre>";
print_r($_POST);
echo "</pre>";