0

I'm trying to increment a php variable with the click of a html button and then call a php function wich uses this variable as a parameter.

The html code simply has two buttons that increase or decrease the current date. When I click on the increase button, I want my $day variable to be increased, passed to the getFromDB($day) function and then run the getFromDB($day) function again.

I've read that I should use ajax for that but I simply don't understand how that would work on the same page. (Also please no form with page reload)

Here's the html code with the 2 buttons

<div class="row dateTitle">
    <div class="col" style="text-align: center; font-size:2em;">
       <button id="prevButton" style="outline:none; background:none; border:none;">
                <  </button> <span id="setDate">15.01.2011</span> <button id="nextButton" style="outline:none; background:none; border:none;">  ></button>
     </div>
</div>

Here is my php function

 <?php

        function getFromDB($day){
        if(!isset($day))
        {
           $day = jddayofweek($julianday [0]);
        }
        $servername = "localhost";
        $username = "****";
        $password = "*****";
        $dbname = "***";

        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);

        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        $dayOfWeek = $day; //jddayofweek($julianday [0]);

        $sql = "SELECT * FROM `courseTimes` JOIN courseNames ON courseTimes.nameID = courseNames.ID WHERE dayOfWeek = " . $dayOfWeek;
        $result = $conn->query($sql);



            if($result->num_rows > 0) {
             while($row = $result->fetch_assoc()){
                echo '<tr>
                    <th scope="row">' .$row["startingTime"]. ' - ' .$row["endingTime"]. '</th>
                    <td style="background-color: rgb(226, 194, 145);">' .$row["cName"]. '<button
                            class="tableButton" onclick="openModal()">(Anmelden)</button></td>
                </tr> ';
             }
            }

         $conn->close();
        }

        getFromDB();
    ?>

The button should simply call the getFromDB($day) function , similiar to the onclick event with javascript.

  • 1
    PHP is processed at the server and the result sent to the browser. You cannot directly interact with PHP once the user has the page in their browser. That’s why you use AJAX, or a form targeting a PHP file. – Chris Aug 26 '19 at 17:30
  • So I should move my php function to a new .php file? –  Aug 26 '19 at 17:32
  • 1
    Yes that would work. Have a look at AJAX, which you call using a javascript function triggered on the button click. Javascript runs in the user’s browser locally. It can send and receive data to a server PHP file and you can then update your page with any returned data without ever having to reload it. – Chris Aug 26 '19 at 18:06

0 Answers0