Jump to content

Can anyone please help!? It's urgent


DaVinc1

Recommended Posts

1 hour ago, DaVinc1 said:

The point of dates is to make a reservation, so I need the past dates (dates before today) to be unclickable because of course it doesn't make sense to make a reservation for yesterday. But can't do it.

Add some extra checks in to prevent the rendering of dates in the table if they are in the past.  This should work:

 

<section class="content" id="termin">
        <?php
        $dt = new DateTime;
        $thisWeek = $dt->format('W');
        $thisYear = $dt->format('o');

        if (isset($_GET['year']) &&  $_GET['year'] >= $thisYear &&
            isset($_GET['week']) && $_GET['week'] >= $thisWeek
        ) {
            $dt->setISODate($_GET['year'], $_GET['week']);
        } else {
            $dt->setISODate($dt->format('o'), $dt->format('W'));
        }
        $year = $dt->format('o');
        $week = $dt->format('W');
        ?>
  • Like 1
Link to comment
Share on other sites

I was offering up a method rather than a spoonfed solution. This is a fuller solution incorporating the dates

<?php
$duration = 45;
$cleanup = 0;
$start = "10:00";
$end = "15:15";

################################################################################
# Default week commence date                                                   #
################################################################################
$d1 = new DateTime();
if ($d1->format('w') <> 1) {
    $d1->modify('last monday');
}

$wkcomm =  $_GET['week'] ?? $d1->format('Y-m-d');

$d1 = new DateTime($wkcomm);
$week1 = $d1->sub(new DateInterval('P7D'))->format('Y-m-d');
$week2 = $d1->add(new DateInterval('P14D'))->format('Y-m-d');

function timeslots($duration, $cleanup, $start, $end)
{
    $start = new DateTime($start);
    $end = new DateTime($end);
    $duration += $cleanup;
    $interval = new DateInterval("PT".$duration."M");

    return new DatePeriod($start, $interval, $end);
}

function daysOfWeek($comm)
{
    $d1 = new DateTime($comm);
    return new DatePeriod($d1, new DateInterval('P1D'), 6);
}

?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>Tehnički pregled</title>
    <script type='text/javascript'>

        $(function() {                                                              // when page has loaded
        
            $(".tslot").click(function() {                                          // define click event listener
                $("#tVreme").val( $(this).data("timeslot") )
            })
        })
        
    </script>
    <style type='text/css'>
        td, th {
            padding: 4px;
            text-align: center;
        }
        th {
            background-color: black;
            color: white;
        }
    </style>
</head>
<body>
    <section class="header">
        <div class="navbar">
            <div class="logo">
                <img src="images/logo.png">
                <span>Tehnički pregled</span>
            </div>
            <div class="nav-links" id="navLinks">
                <ul>
                    <li><a aria-current="page" href="index.php">Naslovna</a></li>
                    <li><a href="galerija.php">Galerija</a></li>
                </ul>
            </div>
        </div>
        <div class="headline">
            <h1>Tehnički pregled</h1>
            <p>Odaberite termin i zakažite tehnički pregled svog vozila brzo i jednostavno na našem sajtu.</p>
            <a href="#termin" class="btn">Zakažite termin</a>
        </div>
    </section>
    <div id="myModal" class="modal">
        <div class="login-box">
            <p>Zakazivanje termina</p>
            <form method="POST">
                <div class="user-box">
                <input name="tIme" type="text" required="Please">
                <label>Ime</label>
                </div>
                <div class="user-box">
                <input name="tPrezime" type="text" required>
                <label>Prezime</label>
                </div>
                <div class="user-box">
                <input name="tTelefon" type="text" required>
                <label>Broj telefona</label>
                </div>
                <div class="user-box">
                <input name="tVreme" id="tVreme" type="text" required readonly>
                <label>Datum i vrijeme</label>
                </div>
                <br>
                <input type='submit' value='POŠALJI'>
            </form>
        </div>
    </div>
    <section class="content" id="termin">

        <br><br>
        <a href='?week=<?=$week1?>'>Previous Week</a>
        &emsp;
        <a href='?week=<?=$week2?>'>Next Week</a>
        <br><br>
        <table>

        <?php
            ####################################################################
            #  BUILD THE TABLE OF TIMESLOTS                                    #
            ####################################################################
            $days = daysOfWeek($wkcomm);
            $times = timeslots($duration, $cleanup, $start, $end);
            $today = new DateTime();
            // table headings
            echo "<tr>";
            foreach ($days as $d) {
                echo '<th>' . $d->format('l<\b\r>d M Y') . '</th>';
            }
            echo "</tr>\n";
            // times
            foreach ($times as $t)  {
                $ts = $t->format('H:i');
                echo "<tr>";
                foreach ($days as $d) {
                    if ($d > $today) {
                        $dt = $d->format('Y-m-d') . ' ' . $ts;
                        echo "<td><a href='#' class='tslot' data-timeslot='$dt' >$ts h</a><?td>";
                    }
                    else {
                        echo "<td>&nbsp;</td>";
                    }
                }
                echo "</tr>\n";
            }
        ?>
            
        </table>
        <span>Odaberite željeno vreme.</span>
    </section>
    <section class="footer">
        <div class="social">
            <ul>
                <li><a href="#"><img src="images/facebook.png" alt=""></a></li>
                <li><a href="#"><img src="images/twitter.png" alt=""></a></li>
                <li><a href="#"><img src="images/gmail.png" alt=""></a></li>
            </ul>
        </div>
        <span>Designed by Filip Glišović &copy2023. - All rights reserved.</span>
    </section>
</body>
</html>

 

  • Like 1
Link to comment
Share on other sites

On 7/3/2023 at 5:20 AM, gizmola said:

Add some extra checks in to prevent the rendering of dates in the table if they are in the past.  This should work:

 

<section class="content" id="termin">
        <?php
        $dt = new DateTime;
        $thisWeek = $dt->format('W');
        $thisYear = $dt->format('o');

        if (isset($_GET['year']) &&  $_GET['year'] >= $thisYear &&
            isset($_GET['week']) && $_GET['week'] >= $thisWeek
        ) {
            $dt->setISODate($_GET['year'], $_GET['week']);
        } else {
            $dt->setISODate($dt->format('o'), $dt->format('W'));
        }
        $year = $dt->format('o');
        $week = $dt->format('W');
        ?>

Omg are you a god? 🤩

Is there maybe a way to make the times (hours) that are reserved or that passed unclickable?
To elaborate, when I make a reservation at 10 o'clock, no one else should be able to, or if the current time is for example 11:42, no one should be able to make reservation at 10:00, 10:45, etc...

Edited by DaVinc1
Link to comment
Share on other sites

2 hours ago, DaVinc1 said:

when I make a reservation at 10 o'clock, no one else should be able to

Query your existing bookings and create an array...

function getBookedSlots($pdo, $wkcomm)
{
    $res = $pdo->prepare("SELECT datum
                               , vreme
                          FROM tehnicki
                          WHERE datum BETWEEN ? AND ? + INTERVAL 6 DAY
                          ");
    $res->execute([ $wkcomm, $wkcomm ]);
    $data = [];
    foreach ($res as $r) {
        $data[$r['datum']][$r['vreme']] = 1;
    }
    return $data;
}

 

$bookings [ '2023-07-05'][ '10:00' ] = 1; 
$bookings [ '2023-07-06'][ '11:30' ] = 1 

then

if ($d > $today && !isset($bookings[$dt][$ts])) {                             // clickable if not booked

Incorporating into my previous code...

<?php
$duration = 45;
$cleanup = 0;
$start = "10:00";
$end = "15:15";

################################################################################
# Default week commence date                                                   #
################################################################################
$d1 = new DateTime();
if ($d1->format('w') <> 1) {
    $d1->modify('last monday');
}

$wkcomm =  $_GET['week'] ?? $d1->format('Y-m-d');

$d1 = new DateTime($wkcomm);
$week1 = $d1->sub(new DateInterval('P7D'))->format('Y-m-d');
$week2 = $d1->add(new DateInterval('P14D'))->format('Y-m-d');

function getBookedSlots($pdo, $wkcomm)
{
    $res = $pdo->prepare("SELECT datum
                               , vreme
                          FROM tehnicki
                          WHERE datum BETWEEN ? AND ? + INTERVAL 6 DAY
                          ");
    $res->execute([ $wkcomm, $wkcomm ]);
    $data = [];
    foreach ($res as $r) {
        $data[$r['datum']][$r['vreme']] = 1;
    }
    return $data;
}

function timeslots($duration, $cleanup, $start, $end)
{
    $start = new DateTime($start);
    $end = new DateTime($end);
    $duration += $cleanup;
    $interval = new DateInterval("PT".$duration."M");

    return new DatePeriod($start, $interval, $end);
}

function daysOfWeek($comm)
{
    $d1 = new DateTime($comm);
    return new DatePeriod($d1, new DateInterval('P1D'), 6);
}

?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>Tehnički pregled</title>
    <script type='text/javascript'>

        $(function() {                                                              // when page has loaded
        
            $(".tslot").click(function() {                                          // define click event listener
                $("#tVreme").val( $(this).data("timeslot") )
                $(".tslot").css('background-color', '#fff')
                $(this).css('background-color', '#ccc')
            })
        })
        
    </script>
    <style type='text/css'>
        td, th {
            padding: 4px;
            text-align: center;
        }
        th {
            background-color: black;
            color: white;
        }
        td {
            color: #999;
        }
    </style>
</head>
<body>
    <section class="header">
        <div class="navbar">
            <div class="logo">
                <img src="images/logo.png">
                <span>Tehnički pregled</span>
            </div>
            <div class="nav-links" id="navLinks">
                <ul>
                    <li><a aria-current="page" href="index.php">Naslovna</a></li>
                    <li><a href="galerija.php">Galerija</a></li>
                </ul>
            </div>
        </div>
        <div class="headline">
            <h1>Tehnički pregled</h1>
            <p>Odaberite termin i zakažite tehnički pregled svog vozila brzo i jednostavno na našem sajtu.</p>
            <a href="#termin" class="btn">Zakažite termin</a>
        </div>
    </section>
    <div id="myModal" class="modal">
        <div class="login-box">
            <p>Zakazivanje termina</p>
            <form method="POST">
                <div class="user-box">
                <input name="tIme" type="text" required="Please">
                <label>Ime</label>
                </div>
                <div class="user-box">
                <input name="tPrezime" type="text" required>
                <label>Prezime</label>
                </div>
                <div class="user-box">
                <input name="tTelefon" type="text" required>
                <label>Broj telefona</label>
                </div>
                <div class="user-box">
                <input name="tVreme" id="tVreme" type="text" required readonly>
                <label>Datum i vrijeme</label>
                </div>
                <br>
                <input type='submit' value='POŠALJI'>
            </form>
        </div>
    </div>
    <section class="content" id="termin">

        <br><br>
        <a href='?week=<?=$week1?>'>Previous Week</a>
        &emsp;
        <a href='?week=<?=$week2?>'>Next Week</a>
        <br><br>
        <table>

        <?php
            ####################################################################
            #  BUILD THE TABLE OF TIMESLOTS                                    #
            ####################################################################
            $days = daysOfWeek($wkcomm);
            $times = timeslots($duration, $cleanup, $start, $end);
            $bookings = getBookedSlots($pdo, $wkcomm);                                           // get current bookings
            $today = new DateTime();
            // table headings
            echo "<tr>";
            foreach ($days as $d) {
                echo '<th>' . $d->format('l<\b\r>d M Y') . '</th>';
            }
            echo "</tr>\n";
            // times
            foreach ($times as $t)  {
                $ts = $t->format('H:i');
                echo "<tr>";
                foreach ($days as $d) {
                    $dt = $d->format('Y-m-d');
                    if ($d > $today && !isset($bookings[$dt][$ts])) {                             // clickable if not booked
                        $dt = $dt . ' ' . $ts;
                        echo "<td><a href='#' class='tslot' data-timeslot='$dt' >$ts h</a><?td>";
                    }
                    else {
                        echo "<td>$ts</td>";
                    }
                }
                echo "</tr>\n";
            }
        ?>
            
        </table>

        <span>Odaberite željeno vreme.</span>
    </section>
    <section class="footer">
        <div class="social">
            <ul>
                <li><a href="#"><img src="images/facebook.png" alt=""></a></li>
                <li><a href="#"><img src="images/twitter.png" alt=""></a></li>
                <li><a href="#"><img src="images/gmail.png" alt=""></a></li>
            </ul>
        </div>
        <span>Designed by Filip Glišović &copy2023. - All rights reserved.</span>
    </section>
</body>
</html>

 

  • Like 2
Link to comment
Share on other sites

Thank you soo much! 
I know I am coming off as spoiled and rude here, and I am so sorry for that, but is there a way to implement it in my code since everything is working perfectly and I'm afraid to touch anything...

I would totally understand if you can't/won't because you've done soo much already and thank you for that from the bottom of my heart.

<?php
$duration = 45;
$cleanup = 0;
$start = "10:00";
$end = "15:15";

function timeslots($duration, $cleanup, $start, $end){
    $start = new DateTime($start);
    $end = new DateTime($end);
    $interval = new DateInterval("PT".$duration."M");
    $cleanupInterval = new DateInterval("PT".$cleanup."M");
    $slots = array();

    for($intStart = $start; $intStart<$end; $intStart->add($interval)->add($cleanupInterval)){
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);
        if($endPeriod>$end){
            break;
        }
         $slots[] = $intStart->format("H:i")." h ";
    }

    return $slots;
}
?>

<?php

if (isset($_POST['tIme']) || isset($_POST['tPrezime']) || isset($_POST['tTelefon']) || isset($_POST['tDatum']) || isset($_POST['tVreme'])) {
    $con = mysqli_connect('localhost', 'root', '','tpozdb');

    $tIme = $_POST['tIme'];
    $tPrezime = $_POST['tPrezime'];
    $tTelefon = $_POST['tTelefon'];
    $tDatum = $_POST['tDatum'];
    $tVreme = $_POST['tVreme'];

    $sql = "INSERT INTO `tehnicki` (`Id`, `Ime`, `Prezime`, `Telefon`, `Datum`, `Vreme`) VALUES ('0', '$tIme', '$tPrezime', '$tTelefon', '$tDatum', '$tVreme')";

    $rs = mysqli_query($con, $sql);
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tehnički pregled</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" type="img/png" href="images/logo.png">
    <meta name="author" content="Filip Glišović, glisovic01@gmail.com">
    <!-- Rubik font -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Moment -->
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
</head>
<body>
    <section class="header">
        <div class="navbar">
            <div class="logo">
                <img src="images/logo.png">
                <span>Tehnički pregled</span>
            </div>
            <div class="nav-links" id="navLinks">
                <ul>
                    <li><a aria-current="page" href="index.php">Naslovna</a></li>
                    <li><a href="galerija.php">Galerija</a></li>
                </ul>
            </div>
        </div>
        <div class="headline">
            <h1>Tehnički pregled</h1>
            <p>Odaberite termin i zakažite tehnički pregled svog vozila brzo i jednostavno na našem sajtu.</p>
            <a href="#termin" class="btn">Zakažite termin</a>
        </div>
    </section>
    <div id="myModal" class="modal">
        <div class="login-box">
            <p>Zakazivanje termina</p>
            <form method="POST">
                <div class="user-box">
                <input name="tIme" type="text" required>
                <label>Ime</label>
                </div>
                <div class="user-box">
                <input name="tPrezime" type="text" required>
                <label>Prezime</label>
                </div>
                <div class="user-box">
                <input name="tTelefon" type="text" required>
                <label>Broj telefona</label>
                </div>
                <div class="user-box">
                <input name="tDatum" type="date" onkeydown="return false" required readonly>
                </div>
                <div class="user-box">
                <input name="tVreme" id="tVreme" type="text" onkeydown="return false" required readonly>
                </div>
                <a href="#" onclick="this.closest('form').submit();">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
                POŠALJI
                </a>
            </form>
        </div>
    </div>
    <section class="content" id="termin">
        <?php
        $dt = new DateTime;
        $thisWeek = $dt->format('W');
        $thisYear = $dt->format('o');
        if (isset($_GET['year']) &&  $_GET['year'] >= $thisYear &&
            isset($_GET['week']) && $_GET['week'] >= $thisWeek
        ) {
            $dt->setISODate($_GET['year'], $_GET['week']);
        } else {
            $dt->setISODate($dt->format('o'), $dt->format('W'));
        }
        $year = $dt->format('o');
        $week = $dt->format('W');
        ?>

        <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Prethodna Nedelja</a>
        <a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Sledeća Nedelja</a>

        <table id="myTable">
            <tr>
            <?php
            do {
                if($dt->format('d m Y') == date('d m Y')){
                    echo "<td id='danas'>" . $dt->format('d m Y') . "<br>" . "~~~" . "</td>\n";
                }else{
                    echo "<td>" . $dt->format('d m Y') . "<br>" . "~~~" . "</td>\n";
                }
                
                $dt->modify('+1 day');
            } while ($week == $dt->format('W'));
            ?>
            </tr>
            <?php $timeslots = timeslots($duration, $cleanup, $start, $end);
                foreach($timeslots as $ts){
            ?>
            <tr>
            <td><a href="#" onclick="MyFunction(0, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            <td><a href="#" onclick="MyFunction(1, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            <td><a href="#" onclick="MyFunction(2, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            <td><a href="#" onclick="MyFunction(3, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            <td><a href="#" onclick="MyFunction(4, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            <td><a href="#" onclick="MyFunction(5, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            <td><a href="#" onclick="MyFunction(6, '<?php echo $ts; ?>');return false;"><?php echo $ts; ?></a></td>
            </tr>
                <?php } ?>
            
        </table>
        <span>Odaberite željeno vreme.</span>
    </section>
    <section class="footer">
        <div class="social">
            <ul>
                <li><a href="#"><img src="images/facebook.png" alt=""></a></li>
                <li><a href="#"><img src="images/twitter.png" alt=""></a></li>
                <li><a href="#"><img src="images/gmail.png" alt=""></a></li>
            </ul>
        </div>
        <span>Designed by Filip Glišović &copy2023. - All rights reserved.</span>
    </section>
    <script src="app.js"></script>
    <script type='text/javascript'>
        function MyFunction(col, time) {
            modal.style.display = "block";
            const tbl = document.getElementById("myTable");
            let dateValue = tbl.rows[0].cells[col].innerHTML;
            dateValue = dateValue.replace(/\D/g,'');
            dateValue = moment(dateValue,"DDMMYYYY").format("YYYY-MM-DD")
            let dateEl = document.getElementsByName("tDatum");
            let timeEl = document.getElementsByName("tVreme");
            dateEl[0].value = dateValue;
            timeEl[0].value = time;
            
            console.log('dateValue: ' + dateValue);
            console.log('Time: ' + time);
        }
    </script>
</body>
</html>

 

Link to comment
Share on other sites

Well, there are some error in your code and you need to update below sections of your code:

<td> elements in the timeslots loop:          

<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
<td><a href="#" onclick="MyFunction('<?php echo $ts; ?>'); return false;"><?php echo $ts; ?></a></td>
 

I hope it will help you.

Thanks   

Link to comment
Share on other sites

I made some huge progress recently, all reserved and past timeslots are blocked, but then I came to the final error.
When you click a certain timeslot, the time gets filled into time input in my modal perfectly, but the date that get's filled into date input is random and I can't figure out why.

For example:
Under the date 10.7.2023. you select any time (timeslot) and it get's filled into the time input perfectly, but the date that get's filled into date input is 14.7.2023.

Please help 🥺

index.php

<?php
$duration = 45;
$cleanup = 0;
$start = "10:00";
$end = "14:30";

require_once 'functions.php';
require_once 'db_connection.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    handleFormSubmission();
}

$dt = getCurrentDateTime();
$year = getYearFromRequest($dt);
$week = getWeekFromRequest($dt);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tehnički pregled</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="icon" type="image/png" href="images/logo.png">
    <meta name="author" content="Filip Glišović, glisovic01@gmail.com">
    <!-- Rubik font -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Moment -->
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
</head>
<body>
    <section class="header">
        <div class="navbar">
            <div class="logo">
                <img src="images/logo.png" alt="">
                <span>Tehnički pregled</span>
            </div>
            <div class="nav-links" id="navLinks">
                <ul>
                    <li><a aria-current="page" href="index.php">Naslovna</a></li>
                    <li><a href="galerija.php">Galerija</a></li>
                </ul>
            </div>
        </div>
        <div class="headline">
            <h1>Tehnički pregled</h1>
            <p>Odaberite termin i zakažite tehnički pregled svog vozila brzo i jednostavno na našem sajtu.</p>
            <a href="#termin" class="btn">Zakažite termin</a>
        </div>
    </section>
    <div id="myModal" class="modal">
        <div class="login-box">
            <p>Zakazivanje termina</p>
            <form method="POST">
                <div class="user-box">
                    <input name="tIme" type="text" required>
                    <label>Ime</label>
                </div>
                <div class="user-box">
                    <input name="tPrezime" type="text" required>
                    <label>Prezime</label>
                </div>
                <div class="user-box">
                    <input name="tTelefon" type="text" required>
                    <label>Broj telefona</label>
                </div>
                <div class="user-box">
                    <input name="tDatum" type="date" onkeydown="return false" required readonly>
                </div>
                <div class="user-box">
                    <input name="tVreme" id="tVreme" type="text" onkeydown="return false" required readonly>
                </div>
                <a href="#" onclick="this.closest('form').submit();alert('Uspešno ste zakazali termin!')">
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    POŠALJI
                </a>
            </form>
        </div>
    </div>
        <section class="content" id="termin">
        <?php include 'time_table.php'; ?>
        <span>Odaberite željeno vreme.</span>
        <p>* Vremena su nedostupna/zauzeta.</p>
    </section>
    <section class="footer">
        <div class="social">
            <ul>
                <li><a href="#"><img src="images/facebook.png" alt=""></a></li>
                <li><a href="#"><img src="images/twitter.png" alt=""></a></li>
                <li><a href="#"><img src="images/gmail.png" alt=""></a></li>
            </ul>
        </div>
        <span>Designed by Filip Glišović &copy2023. - All rights reserved.</span>
    </section>
    <script src="app.js"></script>
</body>
</html>


functions.php

<?php

function timeslots($duration, $cleanup, $start, $end)
{
    $startDateTime = new DateTime($start);
    $endDateTime = new DateTime($end);
    $interval = new DateInterval("PT" . $duration . "M");
    $cleanupInterval = new DateInterval("PT" . $cleanup . "M");
    $slots = array();

    $currentDateTime = clone $startDateTime;

    while ($currentDateTime <= $endDateTime) {
        $slots[] = $currentDateTime->format("H:i") . " h";
        $currentDateTime->add($interval)->add($cleanupInterval);
    }

    return $slots;
}

function checkTimeslotRegistration($timeslot, $date)
{
    global $con;

    $query = "SELECT COUNT(*) FROM `tehnicki` WHERE `Vreme` = ? AND DATE(`Datum`) = ?";
    $stmt = mysqli_prepare($con, $query);
    mysqli_stmt_bind_param($stmt, 'ss', $timeslot, $date);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $countResult);
    mysqli_stmt_fetch($stmt);
    mysqli_stmt_close($stmt);

    $count = $countResult;

    return $count > 0;
}

function handleFormSubmission()
{
    global $con;

    $tIme = $_POST['tIme'] ?? '';
    $tPrezime = $_POST['tPrezime'] ?? '';
    $tTelefon = $_POST['tTelefon'] ?? '';
    $tDatum = $_POST['tDatum'] ?? '';
    $tVreme = $_POST['tVreme'] ?? '';

    $stmt = mysqli_prepare($con, "INSERT INTO `tehnicki` (`Id`, `Ime`, `Prezime`, `Telefon`, `Datum`, `Vreme`) VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($stmt, 'isssss', $id, $tIme, $tPrezime, $tTelefon, $tDatum, $tVreme);

    $id = 0;

    if (mysqli_stmt_execute($stmt)) {
        mysqli_stmt_close($stmt);
        mysqli_close($con);
        header("Location: index.php");
        exit();
    } else {
        mysqli_stmt_close($stmt);
        mysqli_close($con);
        die("Error: " . mysqli_error($con));
    }
}

function getCurrentDateTime()
{
    $timezone = new DateTimeZone('Europe/Belgrade');
    return new DateTime('now', $timezone);
}

function getYearFromRequest($dt)
{
    $thisYear = $dt->format('o');
    return isset($_GET['year']) && $_GET['year'] >= $thisYear ? $_GET['year'] : $thisYear;
}

function getWeekFromRequest($dt)
{
    $thisWeek = $dt->format('W');
    return isset($_GET['week']) && $_GET['week'] >= $thisWeek ? $_GET['week'] : $thisWeek;
}

?>


time_table.php

<?php
$dt = new DateTime();
$thisWeek = $dt->format('W');
$thisYear = $dt->format('o');
if (isset($_GET['year']) && $_GET['year'] >= $thisYear &&
    isset($_GET['week']) && $_GET['week'] >= $thisWeek
) {
    $dt->setISODate($_GET['year'], $_GET['week']);
} else {
    $dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>

<a href="<?php echo $_SERVER['PHP_SELF'] . '?week=' . ($week - 1) . '&year=' . $year; ?>">Prethodna Nedelja</a>
<a href="<?php echo $_SERVER['PHP_SELF'] . '?week=' . ($week + 1) . '&year=' . $year; ?>">Sledeća Nedelja</a>

<table id="myTable">
    <tr>
        <?php
        $weekStart = clone $dt;
        $weekStart->modify('Monday this week');
        $weekEnd = clone $weekStart;
        $weekEnd->modify('+6 days');

        $currentDate = clone $weekStart;
        while ($currentDate <= $weekEnd) {
            if ($currentDate->format('d m Y') == date('d m Y')) {
                echo "<td id='danas'>" . $currentDate->format('d.m.Y.') . "<br>~~~</td>";
            } else {
                echo "<td>" . $currentDate->format('d.m.Y.') . "<br>~~~</td>";
            }
            $currentDate->modify('+1 day');
        }
        ?>
    </tr>
    <?php
    $timeslots = timeslots($duration, $cleanup, $start, $end);
    $colIndex = 0;
    $currentDateTime = new DateTime();
    $currentDateTime->setTimezone(new DateTimeZone('Europe/Belgrade'));

    foreach ($timeslots as $timeslot) {
        echo "<tr>";
        $currentDate = clone $weekStart;
        $endDate = clone $weekEnd;
            
        while ($currentDate <= $endDate) {
            $currentDateString = $currentDate->format('Y-m-d');
            $timeslot = rtrim($timeslot, ' h');
            
            $timeslotDateTime = DateTime::createFromFormat('H:i', $timeslot);
            
            if ($timeslotDateTime === false) {
                echo "Invalid timeslot format: " . $timeslot;
                continue;
            }
            
            $timeslotDateTime->setDate($currentDate->format('Y'), $currentDate->format('m'), $currentDate->format('d'));
            $formattedTimeslot = $timeslotDateTime->format("H:i");
            
            $isRegistered = checkTimeslotRegistration($timeslot, $currentDateString);
            $isPast = $timeslotDateTime <= $currentDateTime;
            
            if ($isRegistered || $isPast) {
                echo "<td class='unavailable'>" . $timeslot . " h" . "</td>\n";
            } else {
                echo "<td><a href='#' onclick=\"MyFunction(" . $colIndex . ", '" . $formattedTimeslot . "'); return false;\">" . $timeslot . " h" . "</a></td>\n";
            }
            
            $currentDate->modify('+1 day');
        }
        $colIndex++;
        echo "</tr>";
    }            
    ?>
</table>


app.js

var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();

m = m < 10 ? "0" + m : m;
d = d < 10 ? "0" + d : d;

document.querySelector('input[name="tDatum"]').value = y + "-" + m + "-" + d;

var modal = document.getElementById("myModal");

window.onclick = function (event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
};

function MyFunction(col, time) {
  const tbl = document.getElementById("myTable");
  if (tbl.rows.length > 0 && col < tbl.rows[0].cells.length) {
    let dateValue = tbl.rows[0].cells[col].innerText;
    dateValue = dateValue.replace(/\D/g, '');
    dateValue = moment(dateValue, "DDMMYYYY").format("YYYY-MM-DD");
    let dateEl = document.getElementsByName("tDatum");
    let timeEl = document.getElementsByName("tVreme");
    dateEl[0].value = dateValue;
    timeEl[0].value = time;

    modal.style.display = "block";
  }
}

 

Link to comment
Share on other sites

  • 3 weeks later...

Well, there are some error in function.

Here is the correct code: 

<?php
$duration = 45;
$cleanup = 0;
$start = "10:00";
$end = "15:15";

function timeslots($duration, $cleanup, $start, $end){
    $start = new DateTime($start);
    $end = new DateTime($end);
    $interval = new DateInterval("PT".$duration."M");
    $cleanupInterval = new DateInterval("PT".$cleanup."M");
    $slots = array();

    for($intStart = $start; $intStart<$end; $intStart->add($interval)->add($cleanupInterval)){
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);
        if($endPeriod>$end){
            break;
        }
        $slots[] = $intStart->format("H:i")." h ";
    }

    return $slots;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $con = mysqli_connect('localhost', 'root', '', 'tpozdb');

    if (mysqli_connect_errno()) {
        die("Failed to connect to MySQL: " . mysqli_connect_error());
    }

    $tIme = $_POST['tIme'];
    $tPrezime = $_POST['tPrezime'];
    $tTelefon = $_POST['tTelefon'];
    $tDatum = $_POST['tDatum'];
    $tVreme = $_POST['tVreme'];

    // Use prepared statement to prevent SQL injection
    $sql = "INSERT INTO `tehnicki` (`Id`, `Ime`, `Prezime`, `Telefon`, `Datum`, `Vreme`) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($con, $sql);
    mysqli_stmt_bind_param($stmt, "isssss", $id, $tIme, $tPrezime, $tTelefon, $tDatum, $tVreme);

    // Set the initial value of $id to 0
    $id = 0;

    // Execute the prepared statement
    if (mysqli_stmt_execute($stmt)) {
        // Success
        echo "Appointment successfully scheduled.";
    } else {
        // Error handling
        echo "Error: " . mysqli_error($con);
    }

    // Close the statement and connection
    mysqli_stmt_close($stmt);
    mysqli_close($con);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Rest of your head section... -->
</head>
<body>
    <!-- Your HTML content... -->
    <div id="myModal" class="modal">
        <!-- Your modal content... -->
    </div>
    <section class="content" id="termin">
        <?php
        // Your PHP code for displaying calendar and time slots goes here...
        ?>
        <table>
            <!-- Your table content... -->
        </table>
        <span>Odaberite željeno vreme.</span>
    </section>
    <script src="app.js"></script>
</body>
</html>

Thanks

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.