1

I have a div statement with two nested divs inside. The first nested div is a form that contains a drop down menu that allows the person to select a basic school subject:

<form id="request" action="<?php echo $_SERVER['PHP_SELF']?> method="post">
        <div id='d2'>

            <p id='p2'>Subject: 
                <select id="s" name="subject">
                    <option value="English">English</option>
                    <option value="Social Studies">Social Studies</option>
                    <option value="Math">Math</option>
                    <option value="Science">Science</option>
                </select>
            </p>
            <input type="button" value="Find"/>

        </div>
</form>

The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:

<div id='div3'>
for ($i=0; $i<count($tutors); $i++)
{
      echo "<div>'".$tutors[$i]."'</div><br/>"
      . '<a href = "SelectedTutor.php">Choose me</a>' . "<br/>";
}
</div>

The array is initialized at the very beginning of the php class by connecting to MySQL and then pulling out tutors from the database that are tutor users and tutor in the subject the student user has selected. Again, please forgive me for any bugs, I'm still learning:

<?php 
if ($_SERVER['REQUEST_METHOD']=='POST')
{
    $sub = $_POST['subject'];

    $con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
    $msg = "";
    if (mysqli_connect_errno())
    {
        $msg = "Failed to connect to MySQL: " . mysqli_connect_error();
        echo $msg;
    }    
    $query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
    $tutors = array();
    while ($row = mysqli_fetch_assoc($query))
    {
        $tutors[] = $row["Username"];
    }
}
else
{
    echo "Failed form.";
}
?>

The problem pressing me the most right now is that failed form is always shown on the screen. I suspect this is because the form has been nested inside a div. Is there any way around this? Or is it a different problem(s)?

I'm also wondering if the code will indeed show what I want in the second nested div, or if there are bugs in that too (I'll style it later).

Sebsemillia
  • 9,366
  • 2
  • 55
  • 70
user2578330
  • 57
  • 1
  • 2
  • 6
  • Are you inside PHP with `
    for ($i=0; $i` or similar.
    – Funk Forty Niner Sep 11 '14 at 19:22
  • OK, added the around the loop. Good point, but I'm still not getting the form to work. – user2578330 Sep 11 '14 at 19:25
  • 2
    This `$sub = $_POST['s'];` should be `$sub = $_POST['subject'];` you're using the `ID` as the POST `id="s"` POST expects a named element not an id. – Funk Forty Niner Sep 11 '14 at 19:25
  • Yeah, I noticed. Changed that, but still not posting. Are my div statements weirdly formatted? Like should I eliminate the div that the other two divs are nested in? It would be a hassle to work around, but if it must be done I'll do it. – user2578330 Sep 11 '14 at 19:27
  • 1
    Another thing missing quote for `action="` should be `action=""` – Funk Forty Niner Sep 11 '14 at 19:29
  • Another thing `` could be `` some browsers don't like `button` as a type, which as much as I could test it without setting up a DB, worked. `button` did not. – Funk Forty Niner Sep 11 '14 at 19:35
  • `if ($_SERVER['REQUEST_METHOD']=='POST')` Well clearly your form isn't POSTing data. I'll bet anything that the missing quotes Fred-ii- pointed out are causing it. Also, if you're sending the form data to the same page, you don't need to specify the action attribute for your form. `
    `
    – WinterMute Sep 11 '14 at 19:52
  • Place `for ($i=0; $i'".$tutors[$i]."'` to read as `echo "
    ".$tutors[$i]."

    "`
    – Funk Forty Niner Sep 11 '14 at 20:36

2 Answers2

0

I am basing my solution. on the following assumption. According too these lines from your post. The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:>>>>>> those line were from your post.

Please read the comment in the code carefull. There i explain what i change and suggestions.

This the code

<!--

<form id="request" action="<?php //echo $_SERVER['PHP_SELF']?> method="post">-->       

    /*
  * The line above is wrong and as you may understand by the comments of other user, 
    you dont need to give anything in the action as you are posting it on the same 
  * page. so you can delete it. and add this line below one.
  */  

        <form action="" method="post">
            <div id='d2'>

            <p id='p2'>Subject: 
                <select id="s" name="subject">
                    <option value="English">English</option>
                    <option value="Social Studies">Social Studies</option>
                    <option value="Math">Math</option>
                    <option value="Science">Science</option>
                </select>
            </p>
            <!--<input type="button" value="Find"/>--->
            <input type="submit" value="Find"/>

        </div>
</form>

<div id='div3'>
    <?php 
//I am leaving these php tag for the reference only that you used it in your original code. 
//You dont need those lines

?>

</div>

<?php 
if ($_SERVER['REQUEST_METHOD']=='POST')
{

    $sub = $_POST['subject'];

    //$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
    $con = mysqli_connect("127.0.0.1", "root", "", "mydb");
    $msg = "";
    if (mysqli_connect_errno())
    {
        $msg = "Failed to connect to MySQL: " . mysqli_connect_error();
        echo $msg;
    }    
    $query = mysqli_query($con, "SELECT * FROM User WHERE Role = 'tutor' AND Subject ='".$sub."'")or die(mysqli_error($con));
   // $tutors = array(); You dont need that line either. 
    while ($row = mysqli_fetch_assoc($query))
    {
        $tutors = $row["username"];

      echo "<div>'".$tutors."'</div><br/>"
      . '<a href = "SelectedTutor.php">Choose me</a>' . "<br/>";





/*
 * **Here is the suggestion**. The link you are giving to 
 * the user is always going to be SelectedTutor.php. 
 * I dont think this what you want. you may want to 
 * show tutor profile or wanna do some thing else when
 *  somebody click on the link. Lets say you want show 
 * the tutor profile. Than you have to run another query. 
 * and should be able to generate link accordingly. 
 * I am giving you hint how you can do it in case you want to do it.
 */ 



 /*
     *  you should change that line to this line link one to this
     * echo "<div>'".$tutors."'</div><br/>"
     * . '<a href = "SelectedTutor.php?tutor='.$tutors.'">Choose me</a>' . "<br/>"; 
     * If you notcie i added this parth after SelectedTutor.php, this one ?tutor='.$tutors.'
     * Than your url will be different when ever user click on the link. 
     * Hope i did not confused you
     */

    }
}

else
{
    echo "Failed form.";
}
?>

And you ask why you are getting message of Failed form. In short why your else statement is running. to understand see the expanation below.

if ($_SERVER['REQUEST_METHOD']=='POST')
{
//I removed the code just left the basic shell so you can understand


}

else
{
    echo "Failed form.";

}

If you read the above code you will understand why you are getting Failed form message each time when you run the code. You will not get this message when you click on submit. Reason: Reason is this, in those lines your saying that if Request method is post, than run this bit of code. and Else echo this message out. means whenever your request method is not post run this else statement.

but the thing is that you only sending post request after clicking on the button. before that, there is no post request. so thats why you are getting this message each time you run your script and than it disappear when you click on submit. cause you send the post request.

English is not the first language if i confused you let me know i will explain it again.

arif_suhail_123
  • 2,509
  • 2
  • 12
  • 16
0

Although you have asked for help with PHP/HTML, this is really a job for jQuery/AJAX. Don't worry, though -- it's much simpler than you might think.

The advantage to using AJAX is that you stay on the same page, and the page does not refresh -- but the dropdown selection is sent to a PHP file (that you specify), the MySQL database is consulted, and a response (in HTML) is returned.

Inside the AJAX success function, (did you hear that? Inside the success function!) you receive the HTML returned by the other PHP file and you then plunk the returned HTML into an existing DIV.

Here are some simple examples:

AJAX request callback using jQuery


(1) You would not need to put DIV d2 into <form> tags. Not necessary with AJAX

(2) Your jQuery code would look like this:

<script type="text/javascript">
    $('#s').change(function(){
        var sub = $(this).val();
        $.ajax({
            type: 'post',
             url: 'my_php_file.php',
            data: 'subj=' +sub,
            success: function(resp){
                $('#div3').html(resp);
            }
        });
    });
</script>

The above script can be placed anywhere in the document, or in the head tags, or included in a separate document.

(3) You must reference the jQuery library, as per the first example in the "AJAX request callback..." link.

(4) There will be no need for the Find button, because the code will fire as soon as the dropdown value is changed. It takes microseconds to communicate with the server and stick the list of tutors in the div3 div.

(5) The div3 div must already exist on the page (but it can be empty).

(6) The PHP file (called my_php_file.php in the code above) would be exactly as you wrote, except that it would create an output variable containing the HTML to be plunked into the div3 div. For example:

<?php 
    if ($_SERVER['REQUEST_METHOD']=='POST'){
        $sub = $_POST['subj'];

        $con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
        $msg = "";
        if (mysqli_connect_errno()){
            $msg = "Failed to connect to MySQL: " . mysqli_connect_error();
            echo $msg;
        }    
        $query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
        $tutors = array();
        while ($row = mysqli_fetch_assoc($query)) {
            $tutors[] = $row["Username"];
        }

        $out = '';
        for ($i=0; $i<count($tutors); $i++) {
              $out .= '<div>' .$tutors[$i]. '</div><br/>
                        <a href = "SelectedTutor.php">Choose me</a><br/>
                    ';
        }

    }else{
        $out = "Failed form.";
    }

    echo $out;
?>

All above code is untested, but could work...

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111