Solved

Alert message in php

Posted on 2009-04-07
12
2,115 Views
Last Modified: 2013-12-13
Hey,

I have found out how to do an alert message but I would like to add an sql query to it. I have to check if a field exists in the database first before the alert message pops up.

If the field exists then an alert message comes up asking if the user wants to replace it. If they click ok then the field is replaced and they get redirected to another page.

I am just not sure how to add the php code in there.

Basically I would like to do this:

$checkMonth = mysql_query("SELECT Exercise_Month FROM Exercise_of_Month WHERE Exercise_Month='$exerciseMonth'");
    if( mysql_num_rows($checkMonth) > 0) {
         //pop up alert message - would you like to replace?
<form name="addMonthlyExercise" action="AddMonthlyExercise.php" method="POST">
            Add to Exercise of the Month: <select id="Month" name="Month">
                                            <option value="01">January</option>
                                            <option value="02">February</option>
                                            <option value="03">March</option>
                                            <option value="04">April</option>
                                            <option value="05">May</option>
                                            <option value="06">June</option>
                                            <option value="07">July</option>
                                            <option value="08">August</option>
                                            <option value="09">September</option>
                                            <option value="10">October</option>
                                            <option value="11">November</option>
                                            <option value="12">December</option>
                                        </select>
            <input type="hidden" name="exerciseID" value="<?php echo $exerciseID;?>" />
            <input type="button" value="Add" onClick="if(confirm('An exercise already exsists for this month. Would you like to replace the exercise?')) { window.location.href='ViewMonthlyExercises.php'}">
        </form>

Open in new window

0
Comment
Question by:tqrecords
  • 5
  • 3
  • 3
  • +1
12 Comments
 
LVL 3

Expert Comment

by:Bivek-jos
ID: 24093862
Hi

you need to ask for confirmation before submitting the form. and if the user clicks ok then you need to perform the replacement action.

Thank you.
0
 

Author Comment

by:tqrecords
ID: 24093886
yes. thats what i want to do and i would like to know HOW to do it
0
 
LVL 14

Expert Comment

by:shobinsun
ID: 24093964
Hello,

Use this:

echo "<script>alert('some_message');</script>";

after

 if( mysql_num_rows($checkMonth) > 0) {
0
ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

 
LVL 3

Expert Comment

by:Duboux
ID: 24102401
No, that's not completely right.
First of all, u'd need a confirm() instead of an alert().

PHP is a serverside language. If you submit a form on a page that is already loaded in the browser, it cannot check on the server-side if a record/field already exists, and popup an alert-box within the form that the user is about to submit. Unless you'd use one of the following:
  1. AJAX
    1. Make a JavaScript function to send the form-field value to another php-page, which is going to check if the field exists, and returns a 1 or 0. Then have JavaScript alert a box, that fills in a hidden form-field:
      function AjaxCheckField(exercisemonth)
          {
              // Show the Mojo !
              var rand = "rand=" + Math.ceil(Math.random() * Math.random() * 1000);
              var dataSource = "checkField.inc.php?" + rand + "&Exercise_Month=" + exercisemonth;

              if(XMLHttpRequestObject) {
                  var obj = document.getElementById(divID);
                  XMLHttpRequestObject.open("GET", dataSource);

                  XMLHttpRequestObject.onreadystatechange = function()
                  {
                      if (XMLHttpRequestObject.readyState == 4 &&
                      XMLHttpRequestObject.status == 200) {
                          var OutCome = XMLHttpRequestObject.responseText;
                          if (OutCome == 1)
                          {
                              var answer = confirm("The thingy already exists... Update ?")
                              if (answer){
                                  document.getElementById('hiddenFormField').value = "update";
                              }
                              else{
                                  document.getElementById('hiddenFormField').value = "";
                              }
                          }
                      }
                  }

                  XMLHttpRequestObject.send(null);
              }
          }
    2. Show the form.
    3. To the form-field add something like: onblur="AjaxCheckField(this.value);"

  2. Preloaded vars in javascript from all the possible database-fields
    1. Fetch all different Exercise_Months from the database:
      $Sql = "SELECT DISTINCT Exercise_Month FROM ... GROUP BY Exercise_Month";
    2. Feed them to JavaScript:
      $PhpArray = array();
      while ($row = mysql_fetch_array($Result, MYSQL_NUM)) {
         $PhpArray[] = $row[0];
      }
      echo "<script>var JavayArray = ['" . implode("', '", $PhpArray) . "'];</script>";
    3. Make a cute JavaScript function that checks if the form-field is  in the JavaArray.
    4. Start showing the form with the onSubmit="CheckField(field-name)" in the <form> tag.

  3. A constant resending of form-fields to the same page
    1. Submit form with fields
    2. Check database for field existence. Reload form with filled in value's, and  the javascript alert that shobinsun gave you, and have it submit the form with all the form-fields again.
    3. Do the database-include/update w/e query you want to do.
I hope there's enough code-snippets in here to get you on your merry way ;)
0
 
LVL 3

Expert Comment

by:Duboux
ID: 24102458
There's a/some typo's in my code above... -_-;

remove this line: var obj = document.getElementById(divID);
0
 

Author Comment

by:tqrecords
ID: 24103343
Duboux:

Thanks very much for the help...But I am sorry because I should have mentioned that I am very new with php and javascript.

All of your options make little sense to me and I am kind of unsure of how to fill in the blanks..

I understand number the best so I would probably like to use that one. I am not sure if I am supposed to do this before the addMonthlyExercise form?

I also have no clue how to make javascript functions to check if field exists in the array.

I will give you the entire code on the test page.

Thanks
<!-- Test page to view exercises and add an exercise to exercise of the month -->
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <?php
            $exerciseID = 3;
 
            include('connection.php');
                mysql_connect($ip,$username,$password);
                @mysql_select_db($database) or die('Could not connect to database: ' . mysql_error());
            $result = mysql_query("SELECT * FROM Exercise WHERE Exercise_Id = '$exerciseID'");
            while($row = mysql_fetch_array($result)) {
                $exerciseID = $row["Exercise_Id"];
                $exerciseName = $row["Exercise_Name"];
                $desc = $row["Description"];
                $disabled = $row["Disabled"];
                $dateCreated = $row["Date_Created"];
                $version = $row["Version"];
                $createdBy = $row["Created_By"];
            }
        ?>
        <form name="displayExercise" action="UpdateClient.php" method="POST">
            Exercise ID: <input type="text" name="ExerciseID"  value="<?php echo $exerciseID;?>" /><br/>
            Exercise Name: <input type="text" name="ExerciseName"  value="<?php echo $exerciseName;?>" /><br/>
            Description: <input type="text" name="Description" value="<?php echo $desc; ?>"/><br/>
            Disabled: <input type="text" name="Disabled"  value="<?php echo $disabled;?>" /><br/>
            Date Created: <input type="text" name="Date Created" value="<?php echo $dateCreated; ?>"/><br/>
            Version: <input type="text" name="Version"  value="<?php echo $version;?>" /><br/>
            Created By: <input type="text" name="CreatedBy" value="<?php echo $createdBy; ?>"/><br/>
        </form>
        <form name="addMonthlyExercise" action="AddMonthlyExercise.php" method="POST">
            Add to Exercise of the Month: <select id="Month" name="Month">
                                            <option value="01">January</option>
                                            <option value="02">February</option>
                                            <option value="03">March</option>
                                            <option value="04">April</option>
                                            <option value="05">May</option>
                                            <option value="06">June</option>
                                            <option value="07">July</option>
                                            <option value="08">August</option>
                                            <option value="09">September</option>
                                            <option value="10">October</option>
                                            <option value="11">November</option>
                                            <option value="12">December</option>
                                        </select>
            <input type="hidden" name="exerciseID" value="<?php echo $exerciseID;?>" />
            <input type="button" value="Add" onClick="if(confirm('An exercise already exsists for this month. Would you like to replace the exercise?')) { window.location.href='ViewMonthlyExercises.php'}">
        </form>
    </body>
</html>

Open in new window

0
 
LVL 3

Accepted Solution

by:
Duboux earned 500 total points
ID: 24103500
Okay, I think there can be only one exercise per month ?
At least that's what I can tell from your script & 1st post.
If so, I'm forseeing some problems, as in a year from now, the month-names are the same, and you're only querying on month-names ;)
To prevent this bug, add a year-column, or use a syntax like MMYYYY (042009)


Anyway, I got lost on what you really wanted by looking at your 2 forms..
The way I made it, is that it uses 1 form, and that it adds a value to a hidden field to show if it must update or or not.

Oh, and I took the easiest way from the 3 methods I posted earlier, to not make you run away screaming :P


<!-- Test page to view exercises and add an exercise to exercise of the month -->
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <?php
            $exerciseID = 3;
 
            include('connection.php');
                mysql_connect($ip,$username,$password);
                @mysql_select_db($database) or die('Could not connect to database: ' . mysql_error());
            
            
            ################################################
            
            // First, fetch all the unique Exercise_Month's
            $checkMonth = mysql_query("SELECT DISTINCT Exercise_Month FROM Exercise_of_Month GROUP BY Exercise_Month");
            $PhpArray = array();
            while($row = mysql_fetch_array($checkMonth, MYSQL_NUM)) {
                $PhpArray[] = $row[0];
            }
            // Echo the javascript stuff to the client.
            ?>
            <script language="javascript">
                var JavaArray = ['<?php echo implode("', '", $PhpArray) ?>'];
                
                function in_array(stringToSearch, arrayToSearch) {   // What can I say.. I <3 php
                    for (s = 0; s < arrayToSearch.length; s++) {
                        thisEntry = arrayToSearch[s].toString();
                        if (thisEntry == stringToSearch) {
                           return true;
                        }
                    }
                    return false;
                }
                
                
                function CheckExistance(month_name) {
                    if (in_array(month_name, JavaArray)) {
                        var answer = confirm("There already is a thingy for this month... Update ?");
                        if (answer){
                            document.displayExercise.update_or_new.value="update";
                            document.displayExercise.yay.value="Update";
                        }
                        else{
                            document.displayExercise.update_or_new.value="";
                            document.displayExercise.yay.value='Add';
                        }
                    }
                }
            </script>
            <?php
            
            ################################################
            
            
            
            $result = mysql_query("SELECT * FROM Exercise WHERE Exercise_Id = '".$exerciseID."'");
            while($row = mysql_fetch_array($result)) {
                $exerciseID = $row["Exercise_Id"];
                $exerciseName = $row["Exercise_Name"];
                $desc = $row["Description"];
                $disabled = $row["Disabled"];
                $dateCreated = $row["Date_Created"];
                $version = $row["Version"];
                $createdBy = $row["Created_By"];
            }
 
        ?>
        <form name="displayExercise" action="UpdateClient.php" method="POST">
            Exercise ID: <input type="text" name="ExerciseID"  value="<?php echo $exerciseID;?>" /><br/>
            Exercise Name: <input type="text" name="ExerciseName"  value="<?php echo $exerciseName;?>" /><br/>
            Description: <input type="text" name="Description" value="<?php echo $desc; ?>"/><br/>
            Disabled: <input type="text" name="Disabled"  value="<?php echo $disabled;?>" /><br/>
            Date Created: <input type="text" name="Date Created" value="<?php echo $dateCreated; ?>"/><br/>
            Version: <input type="text" name="Version"  value="<?php echo $version;?>" /><br/>
            Created By: <input type="text" name="CreatedBy" value="<?php echo $createdBy; ?>"/><br/>
<!--
        </form>
        <form name="addMonthlyExercise" action="AddMonthlyExercise.php" method="POST">
//-->
            <input type="hidden" name="update_or_new" value="" />
            Add to Exercise of the Month: <select id="Month" name="Month" onchange="CheckExistance(this.value);">
                                            <option value="01">January</option>
                                            <option value="02">February</option>
                                            <option value="03">March</option>
                                            <option value="04">April</option>
                                            <option value="05">May</option>
                                            <option value="06">June</option>
                                            <option value="07">July</option>
                                            <option value="08">August</option>
                                            <option value="09">September</option>
                                            <option value="10">October</option>
                                            <option value="11">November</option>
                                            <option value="12">December</option>
                                        </select>
            <input type="hidden" name="exerciseID" value="<?php echo $exerciseID;?>" />
            <input type="submit" name="yay" value="Add" />
        </form>
    </body>
</html>

Open in new window

0
 
LVL 3

Expert Comment

by:Bivek-jos
ID: 24103827
Hi

in the onclick event of the submit button add the following line:

onClick="if(confirm('An exercise already exsists for this month. Would you like to replace the exercise?')) { window.location.href='ViewMonthlyExercises.php';return true;}else{return false;}"

Thank you.
0
 
LVL 3

Expert Comment

by:Bivek-jos
ID: 24103841
Hi

Hope the above single line helps you :)

Thank you.
0
 

Author Comment

by:tqrecords
ID: 24113386
Hey guys,

Thank you very much for helping me, but I am kind of confused.

Duboux:

I get your idea of adding the hidden value. That way I can do the update and the add queries in one page. Originally I was just going to make two pages. If the exercise doesn't exist for the month it will send it to the AddMonthlyExercise and if it does and the user clicks yes it will send it to the UpdateMonthlyExercise. Your way is more efficient.

And from testing your code. It only worked for me once and I cannot get it to work again. Your idea is that when the user changes the month it will check if it exists then pop up the message. I don't know why it is not working again.

Regardless, I really need it so that when after the user clicks the button it does the check. Is there any way to do that?

Also when adding this line of code to the Add button:

onClick="if(confirm('An exercise already exsists for this month. Would you like to replace the exercise?')) { window.location.href='ViewMonthlyExercises.php';return true;}else{return false;}"

It pops up every time regardless of the exercise of month existing or not..
 

0
 

Author Comment

by:tqrecords
ID: 24113403
Duboux:

By the way. The reason I have two forms is because we already have a separate exercise display page that is totally different.

The addMonthlyExercise form is separate so we can just insert it in any of our other pages.

Thank you
0
 

Author Comment

by:tqrecords
ID: 24113685
I was hoping it could work like this:

<input type="submit" name="addExercise" value="Add" onclick="CheckExistance(document.Month.value);" />

Obviously it doesn't!!

I supplied my current code below as well as the AddUpdateMonthlyExercise page for further understanding.

Thanks.
<!-- Test page to view exercises and add an exercise to exercise of the month -->
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <?php
            $exerciseID = 3;
 
            include('connection.php');
                mysql_connect($ip,$username,$password);
                @mysql_select_db($database) or die('Could not connect to database: ' . mysql_error());
            
            // First, fetch all the unique Exercise_Month's
            $checkMonth = mysql_query("SELECT Exercise_Month FROM Exercise_of_Month GROUP BY Exercise_Month");
            $PhpArray = array();
            while($row = mysql_fetch_array($checkMonth, MYSQL_NUM)) {
                $PhpArray[] = $row[0];
            }
            // Echo the javascript stuff to the client.
            ?>
            <script language="javascript">
                var JavaArray = ['<?php echo implode("', '", $PhpArray) ?>'];
                
                function in_array(stringToSearch, arrayToSearch) {  
                    for (s = 0; s < arrayToSearch.length; s++) {
                        thisEntry = arrayToSearch[s].toString();
                        if (thisEntry == stringToSearch) {
                           return true;
                        }
                    }
                    return false;
                }
                function CheckExistance(month_name) {
                    if (in_array(month_name, JavaArray)) {
                        var answer = confirm("An exercise already exists for this month. Would you like to replace the exercise?");
                        if (answer) {
                            document.addMonthlyExercise.addUpdate.value="Update";
                            document.addMonthlyExercise.addExercise.value="Update";
                        }
                        else {
                            document.addMonthlyExercise.addUpdate.value="Add";
                            document.addMonthlyExercise.addExercise.value='Add';
                        }
                    }
                }
            </script>
            <?php
 
            $result = mysql_query("SELECT * FROM Exercise WHERE Exercise_Id = '$exerciseID'");
            while($row = mysql_fetch_array($result)) {
                $exerciseID = $row["Exercise_Id"];
                $exerciseName = $row["Exercise_Name"];
                $desc = $row["Description"];
                $disabled = $row["Disabled"];
                $dateCreated = $row["Date_Created"];
                $version = $row["Version"];
                $createdBy = $row["Created_By"];
            }
        ?>
        <form name="displayExercise" method="POST">
            Exercise ID: <input type="text" name="ExerciseID"  value="<?php echo $exerciseID;?>" /><br/>
            Exercise Name: <input type="text" name="ExerciseName"  value="<?php echo $exerciseName;?>" /><br/>
            Description: <input type="text" name="Description" value="<?php echo $desc; ?>"/><br/>
            Disabled: <input type="text" name="Disabled"  value="<?php echo $disabled;?>" /><br/>
            Date Created: <input type="text" name="Date Created" value="<?php echo $dateCreated; ?>"/><br/>
            Version: <input type="text" name="Version"  value="<?php echo $version;?>" /><br/>
            Created By: <input type="text" name="CreatedBy" value="<?php echo $createdBy; ?>"/><br/>
        </form>
        <form name="addMonthlyExercise" action="AddUpdateMonthlyExercise.php" method="POST">
            <input type="hidden" name="addUpdate" value="" />
            Add to Exercise of the Month: <select id="Month" name="Month">
                                            <option value="01">January</option>
                                            <option value="02">February</option>
                                            <option value="03">March</option>
                                            <option value="04">April</option>
                                            <option value="05">May</option>
                                            <option value="06">June</option>
                                            <option value="07">July</option>
                                            <option value="08">August</option>
                                            <option value="09">September</option>
                                            <option value="10">October</option>
                                            <option value="11">November</option>
                                            <option value="12">December</option>
                                        </select>
            <input type="hidden" name="exerciseID" value="<?php echo $exerciseID;?>" />
            <input type="submit" name="addExercise" value="Add" onclick="CheckExistance(document.Month.value);" />
        </form>
    </body>
</html>
 
 
 
 
<?php
/*
	AddUpdateMonthlyExercise.php
    Adds or updates an exercise on the monthly exercise table
*/
	include('connection.php');
        mysql_connect($ip,$username,$password);
        @mysql_select_db($database) or die( "Unable to select database");
	
	$exerciseID = mysql_real_escape_string(stripslashes($_POST['exerciseID']));
	$exerciseMonth = mysql_real_escape_string(stripslashes($_POST['Month']));
    $addUpdate = mysql_real_escape_string(stripslashes($_POST['addUpdate']));
 
    echo "Month: ".$exerciseMonth;
    echo "<br>ID: ".$exerciseID;
    echo "<br>SQL Query: ".$addUpdate;
 
//    Check if value passed in is add or update
    if ($addUpdate == "Update") {
        $sql = mysql_query("UPDATE Exercise_of_Month
            SET Exercise_Id = '$exerciseID'
            WHERE Exercise_Month = '$exerciseMonth'");
 
        if (mysql_query($sql)) {
            echo "<br>Exercise of the month updated";
        }
        else
            echo "<br>Update Failed";
 
        mysql_close();
    }
    else {
        $sql = "INSERT INTO Exercise_of_Month
            SET Exercise_Id = '$exerciseID', Exercise_Month = '$exerciseMonth'";
 
        if (mysql_query($sql)) {
            echo "<br>New exercise of the month added";
        }
        else
            echo "<br>Insert Failed";
 
        mysql_close();
    }
 
//    header('Location: ViewMonthlyExercises.php' );
 
?>

Open in new window

0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question