My time slots are not booked - php

I want to create a basic time slot booking system. But I've run into some problems.
I have created a calendar where I can see that something is happening on a speific date:
It takes the information from my database table. I'm using PHPMyAdmin, and I've added the date manually in there.
As you can see in the table, I would also like to use a start time and an endtime.
If I click a date in my calendar, I create the add-event link like this:
<?php
if (isset ( $_GET ['v'] )) {
echo "<a href='test.php . ?month=" . $month . "&day=" . $day . "&year=" . $year . "&v=true&f=true'>Add Event</a>";
if (isset ( $_GET ['f'] )) {
include ("test.php");
}
$sqlEvent = "SELECT * FROM calendar WHERE eventDate='" . $month . "/" . $day . "/" . $year . "'";
$resultEvents = mysqli_query ( $mysqli1, $sqlEvent );
echo "<br>";
while ( $events = mysqli_fetch_array ( $resultEvents ) ) {
}
}
?>
Clicking this makes my url look somehting like this: test.php%20.%20?month=04&day=18&year=2014&v=true&f=true#
I've included my whole test.php file:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbname = "calendar";
$error = 'Cannot connect to the database';
$mysqli1 = new mysqli ( $hostname, $username, $password, $dbname ) or die ( $error );
if (isset ( $_GET ['day'] )) {
$day = $_GET ['day'];
} else {
$day = date ( "j" );
}
if (isset ( $_GET ['month'] )) {
$month = $_GET ['month'];
} else {
$month = date ( "n" );
}
if (isset ( $_GET ['year'] )) {
$year = $_GET ['year'];
} else {
$year = date ( "Y" );
}
$dateToCompare = $month . '/' . $day . '/' . $year;
echo "<br/><br/><h3>Reservations</h3>";
$timearray = array(8,9,10,11,12,13,14,15,16,17,18,19,20,21,22);
$tablecolor = 1;
echo "<table style='width: 90%;'>";
echo "<tr>";
echo "<th>";
echo "Time";
echo "</th>";
echo "<th>";
echo "Status";
echo "</th>";
echo "</tr>";
foreach ($timearray as $timearrays) {
if($tablecolor %2 == 0) {
echo "<tr>";
}
else {
echo "<tr style='background-color: rgb(0,100,255); background: rgb(0,100,255);'>";
}
echo "<th>";
if ($timearrays == 8) {echo "<h3>8-9am</h3>";}
if ($timearrays == 9) {echo "<h3>9-10am</h3>";}
if ($timearrays == 10) {echo "<h3>10-11am</h3>";}
if ($timearrays == 11) {echo "<h3>11-12am</h3>";}
if ($timearrays == 12) {echo "<h3>12-13am</h3>";}
if ($timearrays == 13) {echo "<h3>13-14am</h3>";}
//Develop your timeslots here to display as required
echo "</th>";
echo "<td>";
$sql = "SELECT * FROM calendar WHERE eventDate='" . $dateToCompare . "'AND timestart >= $timearrays AND endtime <= $timearrays;";
$result = mysqli_query($mysqli1,$sql);
if (mysqli_num_rows($result) == 0) {
echo "<a href='#'><h3 style='color: rgb(255,0,0);'>Reserve</h3></a>";
} else {
echo "<h3>Not Available, taken by someone</h3>";
while($row = mysql_fetch_array($result)) {
echo "<br />";
}
}
echo "</td>";
echo "</tr>";
$tablecolor++;
}
echo "</table>";
?>
As you can see, I try to display my timeslots: $sql = "SELECT * FROM calendar WHERE eventDate='" . $dateToCompare . "'AND timestart >= $timearrays AND endtime <= $timearrays;";
I think that I get my dates correctly from the URL, but I don't see any reservations for a given date.
I hope that some of you can help me out. And please ask, if I need to provide more of my code.
Or if anyone has a better idea on how to do this, please share.
I'm not really sure if I should be conserned about time. I basically just want the ability to click on "Reserve" and then reverse that specific time slot. So maybe a start and an end time isn't nessary?

Try to debug your application. But I guess the problem will probably be the $timearrays in the query you create. I don't think (haven't tested) it works that way.
My suggestion, print out $sql after you've initialized it and see what it returns. Then open PHPmyadmin (which I guess you're using, by the looks of your data) and see what it returns there.

Related

PHP loop HTML table for each user

I have a PHP loop which draws a table based off a MYSQLi query.
What i would like to do is create this table based on a userid (in my case the column called 'badgeid')
At the moment its creating one table
$sql = "SELECT first_name,last_name,signintime,signouttime FROM `signin_entries` WHERE iscleaner ='YES' AND signindate = curdate()";
$list_visitors_result=mysqli_query($con,$sql);
$count_visitors = mysqli_num_rows($list_visitors_result);
if($count_visitors != 0) {
while($row = mysqli_fetch_array($list_visitors_result)){
$signintime = $row['signintime'];
$signouttime = $row['signouttime'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo " <tr><td>$firstname $lastname</td>
<td>$signintime</td>";
if ($signouttime == ""){
echo "<td>Not Signed Out Yet</td>";
} else {
echo "<td>$signouttime</td>";
}
$timeFirst = strtotime(date("Y/m/d") . " " . $signintime);
$timeSecond = strtotime(date("Y/m/d") ." " . $signouttime);
//below checks if th second time is less than the first time than it must be from the day before so add 24 hours eg (signin time 23:30:00 signout time 07:30:30 would be 08:00:30 difference)
if ($timeSecond < $timeFirst)
{
$timeSecond = $timeSecond + 86400;
}
if ($signouttime == ""){
echo "<td>Cleaner Has Not Signed Out Yet</td>";
} else {
$differenceInSeconds = $timeSecond - $timeFirst;
echo "<td class='rowDataSd'>".converttime($differenceInSeconds)."</td>";
}
echo "</tr>";
}
}
//below function converts the seconds difference into hh:mm:ss format to the nearest second
function converttime($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
echo "<tr><th></th><th></th><th></th><th>Total Time Worked</th><tr><td></td><td></td><td></td><td class='totalCol'>Total:</td></tr>";
?>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
Which is great but i really need a table per 'badgeid'
You could do it like that:
$sql = "SELECT first_name,last_name,signintime,signouttime FROM `signin_entries` WHERE iscleaner ='YES' AND signindate = curdate() ORDER BY badgeid ASC";
$list_visitors_result=mysqli_query($con, $sql);
$count_visitors = mysqli_num_rows($list_visitors_result);
if ($count_visitors != 0) {
echo '<table>';
$current_badgeid = '';
while ($row = mysqli_fetch_array($list_visitors_result)) {
if ($current_badgeid == '') {
$current_badgeid = $row['badgeid']; //define if empty, for the first table
}
if($row['badgeid'] != $current_badgeid){
echo '</table><table>';
$current_badgeid = $row['badgeid'];
}
$signintime = $row['signintime'];
$signouttime = $row['signouttime'];
$firstname = $row['first_name'];
$lastname = $row['last_name'];
echo " <tr><td>$firstname $lastname</td><td>$signintime</td>";
if ($signouttime == "") {
echo "<td>Not Signed Out Yet</td>";
} else {
echo "<td>$signouttime</td>";
}
$timeFirst = strtotime(date("Y/m/d") . " " . $signintime);
$timeSecond = strtotime(date("Y/m/d") ." " . $signouttime);
//below checks if th second time is less than the first time than it must be from the day before so add 24 hours eg (signin time 23:30:00 signout time 07:30:30 would be 08:00:30 difference)
if ($timeSecond < $timeFirst) {
$timeSecond = $timeSecond + 86400;
}
if ($signouttime == "") {
echo "<td>Cleaner Has Not Signed Out Yet</td>";
} else {
$differenceInSeconds = $timeSecond - $timeFirst;
echo "<td class='rowDataSd'>".converttime($differenceInSeconds)."</td>";
}
echo "</tr>";
}
echo '</table>';
}
First, you add ORDER BY badgeid ASC to your query. Then you open a table before the loop starts, and you define a $current_badgeid var. Each time the badgeid changes, you close and reopen a table.

Add pagination to my search engine

How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md

Dynamically change selected state of dropdown(s) for each row of data

I'd like to show dropdown menu(s) that contain the selected day based on what is recorded on the database.
Is there any efficient way to dynamically change the selected state of the dropdown menu based on the recorded data?
Thank you
note:
There will be many dropdown menu(s) if the recorded day of the following clinicID is more than one row
The $day is an integer, 1 for Sunday, 2 for Monday and so on
Here is mycode
// Check if any row existed
if ($count>0) {
// If row existed then start printing it
while($row = mysql_fetch_assoc($retval))
{
$day = $row['day'];
$startHour = $row['startHour'];
$startMin = $row['startMin'];
$endHour = $row['endHour'];
$endMin = $row['endMin'];
echo
"<span>" .
"<select name='day[]'>" .
"<option value='1' selected='selected'>Sunday</option>" .
"<option value='2'>Monday</option>" .
"<option value='3'>Tuesday</option>" .
"<option value='4'>Wednesday</option>" .
"<option value='5'>Thursday</option>" .
"<option value='6'>Friday</option>" .
"<option value='7'>Saturday</option>" .
"<option value='0'>Everyday</option>" .
"</select>"
//Please ignore this below
"<br>start : " . $startHour . "." . $startMin .
"<br>end : " . $endHour . "." . $endMin .
"<br><br>";
}
}
else {
}
If this is new code, please use PDO or MySQLi. mysql is depreciated and should not be used on new code php.net/manual/en/function.mysql-query.php Try this link, it helped me a lot: phpdelusions.net/pdo
Change your code to something like this (This code includes PDO implementation):
<?php
$db = new PDO('mysql:host=yourhost;dbname=dbname', 'username', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Printing schedule already in the database
$getbusinesshours = "select * from businesshours where clinicID = $clinicID";
$stmt = $db->prepare($getbusinesshours);
$stmt->execute();
$count = $stmt->rowCount();
// Check if any row existed
if ($count>0){
// If row existed then start printing it
foreach ($stmt as $row){
{
$day = $row['day'];
$startHour = $row['startHour'];
$startMin = $row['startMin'];
$endHour = $row['endHour'];
$endMin = $row['endMin'];
$i = 0;
$days = array('Everyday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
$select = '<span><select name="day[]">';
while($i <= 7){
if($i == $day){
$selected = 'selected="selected"';
}
else{
$selected = '';
}
$select = $select.
'<option value="'.$i.'"'.$selected.'>'.$days[$i].'</option'>
$i++;
}
$select = $select.'</select>';
echo $select;
//Please ignore this below
"<br>start : " . $startHour . "." . $startMin .
"<br>end : " . $endHour . "." . $endMin .
"<br><br>";
}
}
else {
}
?>
I hope this helps.

TimeClock Application: Get time difference between in/out punches

I am creating a time clock application. I have set it up so each user has their own table and it would select that table and all the rows in that table. I want to figure out how to get the difference between the in and next out punch. I am assuming that each in punch will correspond with the next out punch (the next row in the table (when ordering by ID)) I can only think of datediff. I know that is the case, but I have no clue how to implement. I am a very new php developer (Just this past week!) I have no clue how to calculate the difference between each in and out. I have looked at this question: calculate the difference of the time between In and out but couldn't figure it out there or here: mysql timeclock. Any help is appreciated.
My exact question is how to get the difference between each in and out punch in a table.
FILE:
<head>
<title>View My Punches</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="http://example.com/time/favicon.ico"/>
</head>
<?php
error_reporting(E_ALL); ini_set('display_errors', 0);
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .connect_error());
}
$userid_value = $_POST['userid'];
$table = "tc_".$userid_value;
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$unixtime = time() + 60*60;
$time_value = date("h:i:s A", $unixtime);
$date_value = date("m/d/Y", $unixtime);
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
$differs = array();
$inout = array();
$current = array('in'=>array(),'out'=>array(),'length'=>'');
foreach ( $row as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if (( !empty($current['in']) && !empty($current['out'])))
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
$stamp = $inout['length'];
$stampformat = $stamp->format('%s');
$stampint = intval($stampformat);
$stampintval = $stampint/3600;
echo $stampintval;
#array_push($differs, );
}
}
?>
&nbsp
&nbsp
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
It will be much simpler to do this in PHP instead of in the database. Let's assume that you've pulled all the records into a variable, $allofit, and that the records are already sorted by your datetime field. Now you need to pair them up into in-out sets.
$inout = array();
$current = array('in'=>array(),'out'=>array(),'length'=>'');
foreach ( $allofit as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if ( !empty($current['in']) && !empty($current['out'])
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
}
}
Note that your current schema can have mis-matched in-out sets. (in # 1:14, in # 1:15, out # 1:40) This code will silently drop the mismatches; you should probably do what you can to make sure mismatches don't happen in the first place.

SQL Syntax Error via php

I'm kinda new to php, this place has been a great help for me so far! Anyway, I have this code
$month = "
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "
";
That's what I get when I echo out $month
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '1070757'
AND MONTH(atc_online) = 07
AND YEAR(atc_online) = 13
When i use this directly into phpMyAdmin, works as a charm, but when I try to do it through a php webpage, I get the syntax error. I'm using php 5.4
Thanks!
Edit: Full Code:
<?php
//open MySQL connection
$mysql = mysqli_connect('host', 'un', 'pass', 'table')
or die ( "MySQL Error: ".mysqli_error() );
//Get and decode residents data
$jsonData = file_get_contents("link");
$phpArray = json_decode($jsonData, true);
//Start Operations
foreach ($phpArray as $key => $value) {
//Get controller hours for today
$vatsimid = $value[vatsimid];
//Get previous month
$pmonth = date("m", strtotime("-35 days") ) ;
$pmonthName = date("M", strtotime("-35 days") ) ;
echo $pmonth;
echo $pmonthName;
//This year or last year?
If (date("M") != "Jan") { //Checks that it's not January of the next year.
$year = date("y");
}
else {
$year = date("y", strtotime("-1 month") );
}
echo $year;
//Search and sum entries during last month
$month = "SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "";
echo $month;
echo "</br> </br>";
$result = mysqli_query($mysql,$month);
$row = mysqli_fetch_assoc($result);
$month_sum = $row['month_sum'];
echo $month_sum;
//Updates data in atclist
$datainsert = "
UPDATE `atclist`
SET " . $monthName . "=" . $month_sum . "
WHERE vatsimid = " . $vatsimid . "";
$insert = mysqli_query($mysql,$datainsert);
if (!$insert)
{
die('Error: ' . mysqli_error($mysql));
}
}
/*
Did you mean:
SELECT SUM(duration) AS month_sum
FROM connlist
WHERE vatsimid = '1070757' AND MONTH(atc_online) = 07 AND YEAR(atc_online) = 13
It looks like $month_sum variable is not set or empty in your UPDATE query.
You can add single quotes like
$datainsert = "
UPDATE atclist
SET ".$monthName."= '".$month_sum."'
WHERE vatsimid= '".$vatsimid."'";

Categories