Appointment Booking System Slots - php

Im trying to make an appointment booking system, in which everything else works, EXCEPT the appointment time slots, in which if, for example, an appointment is set at 11.30am, and lasts an hour (12.30pm), no one can book or have an appointment within these times.
I have converted start and end times of the input to unix time, as well as converting the times already set in the database, but it is failing me.
I have tried comparing the end time in between the two times set by the user, and the end time of the user between the two times already in the database.
My code is:
if ($length == "1 Hour"){
$edittime = $time;
$timeedit = strtotime($edittime)+3600;
$endtime = date('h:i:s', strftime($timeedit));
} elseif ($length == "1 Hour 30 Minutes") {
$edittime = $time;
$timeedit = strtotime($edittime)+5400;
$endtime = date('h:i:s', strftime($timeedit));
} elseif ($length == "2 Hour") {
$edittime = $time;
$timeedit = strtotime($edittime)+7200;
$endtime = date('h:i:s', strftime($timeedit));
} else {
header("location:Cancel.php");
}
/*Comparison of the start and end times, as well as the user input time.*/
$querysql = "SELECT Time FROM $tablename WHERE Time <= '$endtime' AND Date = '$date'";
$queryresult = mysqli_query($connection, $querysql);
/*Validate the query.*/
if (! $queryresult) {
echo ("Could not retrieve the sql data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
/*Array to collect data from the sql query, to compare against the appointment times the user entered.*/
$count = 0;
$starttime = $time;
$secondtime = strtotime($starttime);
$existapp[$count] = mysqli_fetch_array($queryresult, MYSQLI_NUM);
while ($existapp[$count] <> "") {
$temp = $existapp[$count];
$acquireddata = $temp[$count];
$appsec = strtotime($acquireddata);
if ($length == "1 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
$existend = date('h:i:s', strftime($existedit));
} elseif ($length == "1 Hour 30 Minutes") {
$existstart = $appsec;
$existedit = $existstart + 3600;
$existend = date('h:i:s', strftime($existedit));
} elseif ($length == "2 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
$existend = date('h:i:s', strftime($existedit));
}
/*$timeedit = end time*/
/*$secondtime = start time*/
/*$existededit = exisiting appointment*/
if ($timeedit <= $existedit and $timeedit >= $existstart) {
header("location:Cancel.php");
}
$count = $count + 1;
}
If you need the whole file then just give me a shout.
I've been searching to no end with this, and after checking the unix times, it should work! But it doesnt! ):
<?php
/*Checks if user is logged in, else redirect to home.*/
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
/*Sets variables as the login to the database, as well as tables of interest.*/
$servername = "";
$username = "";
$password = "";
$dbname = "";
$tablename = "appointmentinformation";
$tablenamed = "clientinformation";
/*Connect to the database server and the database.*/
$connection = mysqli_connect("$servername", "$username", "$password", "$dbname") or die("Could not connect to the database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*Retrieve the username from the current session.*/
$clientusername = $_SESSION['Username'];
/*Retrieve the ClientID of interest from a table, with a parameter of the username. Limit the amount of results to one row (one result).*/
$sql = "SELECT ClientID FROM $tablenamed WHERE Username = '$clientusername' LIMIT 1";
/*Validate the query.*/
$results = mysqli_query($connection, $sql);
if (! $results) {
echo ("Could not select the data : " . mysql_error());
} else {
$datarows = mysqli_fetch_row($results);
$clientid = $datarows[0];
}
/*Retrieve user input.*/
$date = $_POST["date"];
$time = $_POST["time"];
$length = $_POST["length"];
/*Format date*/
$date = str_replace('/', '-', $date);
/*Protection from SQL injection attacks.*/
$date = stripslashes($date);
$time = stripslashes($time);
$length = stripslashes($length);
$date = mysqli_real_escape_string($connection, $date);
$time = mysqli_real_escape_string($connection, $time);
$length = mysqli_real_escape_string($connection, $length);
if ($length == "1 Hour"){
$edittime = $time;
$timeedit = strtotime($edittime)+3600;
} elseif ($length == "1 Hour 30 Minutes") {
$edittime = $time;
$timeedit = strtotime($edittime)+5400;
} elseif ($length == "2 Hour") {
$edittime = $time;
$timeedit = strtotime($edittime)+7200;
} else {
header("location:Cancel.php");
}
/*Comparison of the start and end times, as well as the user input time.*/
$querysql = "SELECT Time FROM $tablename WHERE Time <= '$endtime' AND Date = '$date'";
$queryresult = mysqli_query($connection, $querysql);
/*Validate the query.*/
if (! $queryresult) {
echo ("Could not retrieve the sql data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
/*Array to collect data from the sql query, to compare against the appointment times the user entered.*/
$count = 0;
$starttime = $time;
$secondtime = strtotime($starttime);
$existapp[$count] = mysqli_fetch_array($queryresult, MYSQLI_NUM);
while ($existapp[$count] <> "") {
$temp = $existapp[$count];
$acquireddata = $temp[$count];
$appsec = strtotime($acquireddata);
if ($length == "1 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
} elseif ($length == "1 Hour 30 Minutes") {
$existstart = $appsec;
$existedit = $existstart + 3600;
} elseif ($length == "2 Hour") {
$existstart = $appsec;
$existedit = $existstart + 3600;
}
/*$timeedit = end time*/
/*$secondtime = start time*/
/*$existededit = exisiting appointment*/
if ($timeedit <= $existedit and $timeedit >= $existstart) {
header("location:Cancel.php");
}
$count = $count + 1;
}
/*SELECT query to retrieve data from the database. A complex query due to two parameters.*/
$sqlquery = "SELECT * FROM $tablename WHERE Date = '$date' AND Time = '$time'";
$sqlresult = mysqli_query($connection, $sqlquery);
/*Validate the query.*/
if (! $sqlresult) {
echo ("Could not retrieve the sql data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
$rows = mysqli_fetch_row($sqlresult);
$date1 = $rows[3];
$time1 = $rows[4];
/*Compare the date and times and validate.*/
if ($date === $date1 && $time = $time1) {
echo("This date/time is taken!");
header("location:CreateAppointmentForm.php");
} else {
/*Insert the data into the database if validation passes.*/
$query = "INSERT INTO appointmentinformation (ClientID, Length, Date, Time) VALUES ('$clientid', '$length', '$date', '$time')";
$result = mysqli_query($connection, $query);
if ($result) {
header("Location:UserCP.php");
} else {
echo ("Could not insert data : " . mysqli_error($connection) . " " . mysqli_errno($connection));
}
}
?>

You should change strftime to strtotime
http://php.net/manual/en/function.strftime.php
http://php.net/manual/en/function.strtotime.php

strftime first parameter is string format, second timestamp http://php.net/manual/en/function.strftime.php but you give timestamp as first parameter: for example calculated here $timeedit = strtotime($edittime)

Related

How to include insert query inside for loop using php?

User will enter like more than one payment card 1.00,cash 2.00,card 10,00,cash 20.00 etc...After these all values insert into payment_details table one by one along with current date.So after this i need to insert data to another table called moneybox table.
Count of total cash and total card will store into money box group by current date.Always two rows ie; card and cash will be there in money table,going to total of cash and card will be store based on current date.
As far as I understand the requirements, this may help...
<?php
if (isset($_POST["getamount"])) {
$getinvoiceid = $_POST['getinvoiceid'];
$getstorepaymode = $_POST['getstorepaymode'];
$getamount = $_POST['getamount'];
$sql1 = "select date from moneybox order by ID desc limit 1";
$result1 = mysqli_query($link, $sql1);
$row1 = mysqli_fetch_array($result1);
//echo json_encode($row1);
$last_moneybox_created_date = $row1['date'];
$sqlclosebalcash = "select closing_balance from moneybox where date='$last_moneybox_created_date' and type='cash'";
$resultclosebal_cash = mysqli_query($link, $sqlclosebalcash);
$rowclosebal_cash = mysqli_fetch_array($resultclosebal_cash);
//echo json_encode($row1);
//$last_moneybox_closingbalanacecash = $rowclosebal_cash['closing_balance'];
$sqlclosebalcard = "select closing_balance from moneybox where date='$last_moneybox_created_date' and type='bank'";
$resultclosebal_card = mysqli_query($link, $sqlclosebalcard);
$rowclosebal_card = mysqli_fetch_array($resultclosebal_card);
//$last_moneybox_closingbalanacecard = $rowclosebal_card['closing_balance'];
$tz = 'Asia/Dubai'; // your required location time zone.
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$todayDate = $dt->format('Y-m-d');
if ($rowclosebal_cash['closing_balance'] == '') {
$last_moneybox_closingbalanacecash = "0.00";
} else {
$last_moneybox_closingbalanacecash = $rowclosebal_cash['closing_balance'];
}
if ($rowclosebal_card['closing_balance'] == '') {
$last_moneybox_closingbalanacecard = "0.00";
} else {
$last_moneybox_closingbalanacecard = $rowclosebal_card['closing_balance'];
}
for ($count = 0; $count < count($getamount); $count++) {
$payamt_clean = $getamount[$count];
$getstorepaymode_clean = $getstorepaymode[$count];
date_default_timezone_set('Asia/Dubai');
$created = date("y-m-d H:i:s");
$query = 'INSERT INTO payment_details (invoiceID,paymentMode,Amount,created)
VALUES ("' . $getinvoiceid . '" , "' . $getstorepaymode_clean . '", "' . $payamt_clean . '", "' . $created . '");
';
mysqli_query($link, $query);
// check whether card or cash or both rows are already there or not
$sql1 = "select * from moneybox WHERE date='$todayDate' AND type='cash' ";
$resultcash = mysqli_query($link, $sql1);
if(mysqli_num_rows($resultcash)) {
$cashMode = 1;
}
else {
$cashMode = 0;
}
$sql1 = "select * from moneybox WHERE date='$todayDate' AND type='bank' ";
$resultcard = mysqli_query($link, $sql1);
if(mysqli_num_rows($resultcard)) {
$cardMode = 1;
}
else {
$cardMode = 0;
}
$cal_closingbalancecash = $last_moneybox_closingbalanacecash - $payamt_clean;
$cal_closingbalancecard = $last_moneybox_closingbalanacecard - $payamt_clean;
switch($getstorepaymode_clean) {
case "CASH":
if($cashMode === 0) {
echo 'Different Date cash'; //insert happen based on the type
$last_moneybox_created_date = $todayDate;
$cashMode = 1;
$query = "INSERT INTO moneybox (type,inflow,date)
VALUES ('cash','$payamt_clean','$todayDate');";
}
else {
echo 'Same Date cash'; //update happen based on type and date
$query = "UPDATE moneybox SET
inflow = inflow + $payamt_clean,
closing_balance= opening_balance + inflow - outflow
WHERE type = 'cash' and date = '$todayDate';";
}
break;
case "CARD":
if($cardMode === 0) {
echo 'Different Date card'; //insert happen based on the type
$last_moneybox_created_date = $todayDate;
$cardMode = 1;
$query = "INSERT INTO moneybox (type,inflow,date)
VALUES ('bank','$payamt_clean','$todayDate');";
}
else {
echo 'Same Date card'; //update happen based on type and date
$query = "UPDATE moneybox SET
inflow = inflow + $payamt_clean,
closing_balance= opening_balance + inflow - outflow
WHERE type = 'bank' and date = '$todayDate';";
}
break;
} // end switch case
if (mysqli_query($link, $query)) {
echo 'paydetails Inserted';
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($link);
}
}
}
?>

Putting Next 30 days into array

I am needing to find the next 30 days and put in array to repeat a scheduling code.
So I would need to have a variable for
$date= "would hold the date";
$day_of_week= "would hold the # value for the day of week";
I am at a loss of where to even start... I am wanting to repeat the following code for each respective day to schedule crews for the next 30 days.
<?
// Connection Script
include 'connection.php';
date_default_timezone_set("America/New_York");
$tomorrow= strtotime('+ 1 day');
$date= date('N', $tomorrow);
// Get all employees who work tomorrow and group by unit//
$units= "select e.user_id, e.station, e.full_name, max(e.level) level, es.unit, es.days, es.start_time, es.end_time from employees e
left join employee_schedule es on es.pid = e.user_id
where es.days like '%$date%' and e.status = 1
group by es.unit";
$units_result= $conn->query($units);
//Roll through all employees who work tomorrow and place then in appropriate unit.
while($row_unit = $units_result->fetch_assoc()) {
if($row_unit['level'] == 3){
$level= 1;
}elseif($row_unit['level'] == 4){
$level= 2;
}elseif($row_unit['level'] == 5){
$level= 3;
}elseif($row_unit['level'] == 8){
$level= 4;
}
//Get Unit ID from each group
$unitid = $row_unit['unit'];
$intime= date('Y-m-d', $tomorrow);
$intime= $intime.' '. $row_unit['start_time'];
$length= '+ 23 hours';
$intimes= strtotime("$intime");
$endtime= strtotime("$length","$intimes" );
$endtime= date('Y-m-d H:i:s', $endtime);
$station= $row_unit['station'];
$timenow= date('Y-m-d H:i:s');
echo "<p>I am scheduling unit number $unitid to be on at $intime and leave at $endtime </p>";
$unitinsert= "insert into schedules (date_time, unit, level_of_service, start_time, end_time, station)
values ('$timenow', $unitid, $level , '$intime', '$endtime', $station)";
if(mysqli_query($conn, $unitinsert)){
echo "Records inserted successfully.";
$unitinid= $conn->insert_id;
echo $unitinid;
} else{
echo "ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn);
}
$employee = "select e.*, es.unit, es.days, pc.email as pemail from employees e
left join employee_schedule es on es.pid = e.user_id
left join phone_carriers pc on pc.id = e.phone_carrier
where es.days like '%$date%'and es.unit = $unitid and e.status = 1";
$employee_result= $conn->query($employee);
if(mysqli_num_rows($employee_result) > 0){
while($row_employee = $employee_result->fetch_assoc()) {
$pid = $unitinid;
$eid= $row_employee['user_id'];
$ephone = $row_employee['mobile_number'];
$emailphone= $row_employee['mobile_number'].''. $row_employee['pemail'];
$unitcrewinsert= "insert into crew_assignment (date_time, pid, crew_member, phone_number, message_number, confirmed)
values ('$timenow', $pid, $eid , '$ephone', '$emailphone', 0)";
if(mysqli_query($conn, $unitcrewinsert)){
echo "Records inserted successfully.";
echo '<p> Crew Inserted </p>';
} else{
echo "<p>ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn).'</p>';
}
}
}
}
Your best bet is to provide a start date and an end date and get the number of days between them. Then it's just a matter of looping through each day and assigning it to an array. Could probably use the same logic to solve the weeks as well.
Example:
$d1 = Carbon::parse($start_date);
$d2 = Carbon::parse($end_date);
$num_days = $d1->diffInDays($d2) + 1;
$dates = array();
for ($i = 1; $i <= $num_days; $i++) {
array_push($dates, date('Y-m-d', strtotime($start_date.' +'.$i.' days')));
}
var_dump($dates);
I am not sure this is the best way, however it works.
<?php
include 'connection.php';
date_default_timezone_set("America/New_York");
// Start date
$date = '2018-05-18';
// End date
$end_date = '2018-05-31';
while (strtotime($date) <= strtotime($end_date)) {
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
$dayn = date('N', strtotime($date));
echo "<p> $date </p>";
echo "<p> $dayn </p>";
$units = "select e.user_id, e.station, e.full_name, max(e.level) level, es.unit, es.days, es.start_time, es.total_hours from employees e
left join employee_schedule es on es.pid = e.user_id
where es.days like '%$dayn%' and e.status = 1
group by es.unit";
$units_result = $conn->query($units);
//Roll through all employees who work tomorrow and place then in appropriate unit.
if($units_result->num_rows > 0){
while ($row_unit = $units_result->fetch_assoc()) {
if ($row_unit['level'] == 3) {
$level = 1;
} elseif ($row_unit['level'] == 4) {
$level = 2;
} elseif ($row_unit['level'] == 5) {
$level = 3;
} elseif ($row_unit['level'] == 8) {
$level = 4;
}
//Get Unit ID from each group
$unitid = $row_unit['unit'];
$intime = $date . ' ' . $row_unit['start_time'];
$total_hours= $row_unit['total_hours'];
$length = "+ $total_hours ";
$intimes = strtotime("$intime");
$endtime = strtotime("$length", "$intimes");
$endtime = date('Y-m-d H:i:s', $endtime);
$station = $row_unit['station'];
$timenow = date('Y-m-d H:i:s');
echo "<p>I am scheduling unit number $unitid to be on at $intime and leave at $total_hours </p>";
$unitinsert = "insert into schedules (date_time, unit, level_of_service, start_time, total_hours, station)
values ('$timenow', $unitid, $level , '$intime', '$total_hours', $station)";
if (mysqli_query($conn, $unitinsert)) {
echo "Records inserted successfully.";
$unitinid = $conn->insert_id;
echo $unitinid;
} else {
echo "ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn);
}
$inspectioninsert= ""
$employee = "select e.*, es.unit, es.days, pc.email as pemail from employees e
left join employee_schedule es on es.pid = e.user_id
left join phone_carriers pc on pc.id = e.phone_carrier
where es.days like '%$dayn%'and es.unit = $unitid and e.status = 1";
$employee_result = $conn->query($employee);
if (mysqli_num_rows($employee_result) > 0) {
while ($row_employee = $employee_result->fetch_assoc()) {
$pid = $unitinid;
$eid = $row_employee['user_id'];
$ephone = $row_employee['mobile_number'];
$emailphone = $row_employee['mobile_number'] . '' . $row_employee['pemail'];
$unitcrewinsert = "insert into crew_assignment (date_time, pid, crew_member, phone_number, message_number, confirmed)
values ('$timenow', $pid, $eid , '$ephone', '$emailphone', 0)";
if (mysqli_query($conn, $unitcrewinsert)) {
echo "Records inserted successfully.";
echo '<p> Crew Inserted </p>';
} else {
echo "<p>ERROR: Could not able to execute $unitinsert. " . mysqli_error($conn) . '</p>';
}
}
}
}
}
}
?>

Insert database with while loop

I want to create a function that select the begin date and end date and then insert into the database. I want to insert the date for every 4 days from 30/8 til 30/9 to the database...
For example:
table
row 1 = 30/8
row 2 = 3/9
row 3 = 7/9
row 4 = 11/9 ... and so on
My php:
<?php
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("test", $con);
$start_date= "2015-08-30";
$end_date= "2015-09-30";
$insert = "INSERT INTO calendar(date)......";
if(mysql_query($insert,$con)) {
echo "<script> alert('Insert Successful'); </script>";
}
else {
echo "<script> alert('Insert Unsuccessful'); </script>";
}
while (strtotime($start_date) <= strtotime($end_date)) {
//echo "$start_date <br>";
$start_date = date ("Y-m-d", strtotime("+4 day", strtotime($start_date)));
}
Think this is what your searching for... let me know anything needed to change...
<?php
$start_date= "2015-08-30";
$end_date= "2015-09-30";
$inc_val = 4;
$start_con_to_time = strtotime($start_date);
$end_con_to_time = strtotime($end_date);
$days_between = ceil(abs($end_con_to_time - $start_con_to_time) / 86400);
for($x=$inc_val+1; $x<=$days_between;)
{
echo date('Y-m-d', strtotime($start_date. ' + ' . $x . 'days'));
echo ' : Add database code here <br>';
$x+=$inc_val;
}
?>

Track code on reset base on day,week,month

I am trying to create a tracker code, which is when a user enter my page, I will record and add the visitor view by 1
The problem with my code is on every monday, it not only reset the week stats, it also reset the month stats, I paste my increment code and reset code in php below.
Thanks for helping me, I try to figure it out for a few days but can't spot where I code wrongly.
This is my ads.php which I run it by do
<img src="ads.php" width="1" height="1">
at every page
This is my ads.php code
include 'conn.php';
$postID = $_GET['pid'];
$todayDate = date("m-d-y");
//Query with postDate
$sql = "SELECT * FROM wp_tracker WHERE postID LIKE '" . $postID . "'";
$result = mysql_query($sql);
$exist = 0;
while ($row = mysql_fetch_array($result)) {
$postDate = $row['postDate'];
$dayView = $row['dayView'];
$weekView = $row['weekView'];
$monthlyView = $row['monthlyView'];
$exist++;
}
if ($exist == 0) {
//create new record
$sql = "INSERT INTO wp_tracker (postID, postDate) VALUES ('$postID ','$todayDate')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
}
if ($exist > 0) {
//if record exist
//check if it same day
if ($postDate == $todayDate) {
//if same day - just increment views
$dayView = $dayView + 1;
$weekView = $weekView + 1;
$monthlyView = $monthlyView + 1;
$sql2 = "UPDATE wp_tracker SET dayView = '$dayView',weekView = '$weekView',monthlyView = '$monthlyView' WHERE postID='$postID '";
$result2 = mysql_query($sql2);
}
}//end if exist
Below is my reset code (reset.php)
$todayDate = date("m-d-y");
//Query with postDate
$sql = "SELECT postDate FROM wp_tracker order by postDate ASC";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$postDate = $row[0];
$timestamp = time();
if ($postDate != $todayDate) {
//a new day -- update dayView to 0
$dayView = 1;
$sql3 = "UPDATE wp_tracker SET postDate= '" . $todayDate . "', dayView = '$dayView'";
$result3 = mysql_query($sql3);
}
if (date('D', $timestamp) === 'Mon') {
$weekView = 1;
$sql3 = "UPDATE wp_tracker SET weekView = '$weekView'";
$result3 = mysql_query($sql3);
}
if (date('d', $timestamp) === '01') {
$monthlyView = 1;
$sql3 = "UPDATE wp_tracker SET monthlyView= '$monthlyView'";
$result3 = mysql_query($sql3);
}

Realtime with AJAX/MySQL multiple variables?

I have an dymamic PHP file that load Data from MySQL database about some relay card, every user have a different amount of relay card. All card have 8 relays (State 1/0), 8 inputs (State 1/0), and 2 analogue input (State from 0 to 1024) this is for every card, some user will have 1 and some other can have 8 and i would like to update this data as fast as possible. I have done a PHP script that trigger all relays information for a specific user, in this case this is the user 2.
I think the best way to do what i want as what i have read is to call it from jQuery, but i don't understand how-o update many variable.
Here is the code i have to get the latest state from MySQL.
Ok here is an update of the code, i have separated completely the data fetching and the GUI creation, so what i want to do, is show in realtime what the get_states_gui.php file fetch from mysql to the gui.php file. Can someone point me in the good direction since i am completely lost right now! THanx a lot here are those 2 files:
The gui.php:
<?php
require_once('config.php');
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
// We create connection to the MySQL database.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$con) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database\n");
}
$req="SELECT * FROM cartes WHERE utilisateur=$user";
$result = mysql_query($req);
if(!$result) {
die('Query failed: ' . mysql_error());
}
$nb_iplab = mysql_num_rows($result);
$b = "1";
while ($ligne = mysql_fetch_assoc($result))
{
extract($ligne);
${'nom'.$b} = $nom;
${'mac'.$b} = $mac;
${'ip'.$b} = $ip;
for ($i=1; $i <= "8"; $i++ )
{
//We set Relays names for each IPLAB and get their states in the MySQL database.
${'nomR'.$i.$b} = ${'nomR'.$i};
$req = "SELECT * FROM states_log WHERE dev='R$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateR'.$i.$b} = $state;
if ( ${'stateR'.$i.$b} == "1" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/toggle_1.png height=28></a>";
}
else if ( ${'stateR'.$i.$b} == "0" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=SR$i target=empty> <img src=img/toggle_0.png height=28></a>";
}
else
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/LED_yellow.png height=28></a>";
}
//We set Inputs names for each IPLAB and get their states in the MySQL database.
${'nomI'.$i.$b} = ${'nomI'.$i};
${'multI'.$i.$b} = ${'multI'.$i};
${'img_onI'.$i.$b} = ${'img_onI'.$i};
${'img_offI'.$i.$b} = ${'img_offI'.$i};
${'img_naI'.$i.$b} = ${'img_naI'.$i};
$req = "SELECT * FROM states_log WHERE dev='I$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateI'.$i.$b} = $state;
if ( ${'stateI'.$i.$b} == "1" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_onI'.$i.$b} height=28>";
}
else if ( ${'stateI'.$i.$b} == "0" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_offI'.$i.$b} height=28>";
}
else
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_naI'.$i.$b} height=28>";
}
// We check for how many times, the Inputs has changed state to 1, and we set them as a variable for counter.
$req = "SELECT count(*) FROM states_log WHERE dev='I$i' AND state='1' AND mac='${'mac'.$b}'";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
list (${'countI'.$i.$b}) = mysql_fetch_row ($result2);
if (isset(${'multI'.$i.$b}))
{
${'countI'.$i.$b} = ${'countI'.$i.$b} * ${'multI'.$i.$b};
}
}
//We set Analog names fir each IPLAB and get their states in the MySQL database.
for ($i=1; $i <= "3"; $i++ )
{
${'nomA'.$i.$b} = ${'nomA'.$i};
${'unitA'.$i.$b} = ${'unitA'.$i};
$req = "SELECT * FROM states_log WHERE dev='A$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateA'.$i.$b} = $state;
}
if ( debug == "1" )
{
echo "${'nom'.$b}<br>";
echo "MAC = ${'mac'.$b}<br>";
for ( $i = 1; $i <= 8; $i++ )
{
echo "${'nomR'.$i.$b} = ${'stateR'.$i.$b}<br>";
echo "${'nomI'.$i.$b} = ${'stateI'.$i.$b}<br>";
}
for ( $i = 1; $i <= 3; $i++ )
{
echo "${'nomA'.$i.$b} = ${'stateA'.$i.$b}<br>";
}
echo "---------------------------------------<br>";
}
$b++;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
if ( debug == "1" )
{
echo 'Page generated in '.$total_time.' seconds.'."\n";
}
mysql_close($con);
?>
And now the get_states_gui.php:
<?php
require_once('config.php');
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
// We create connection to the MySQL database.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$con) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database\n");
}
$req="SELECT * FROM cartes WHERE utilisateur=$user";
$result = mysql_query($req);
if(!$result) {
die('Query failed: ' . mysql_error());
}
$nb_iplab = mysql_num_rows($result);
$b = "1";
while ($ligne = mysql_fetch_assoc($result))
{
extract($ligne);
${'nom'.$b} = $nom;
${'mac'.$b} = $mac;
${'ip'.$b} = $ip;
for ($i=1; $i <= "8"; $i++ )
{
//We set Relays names for each IPLAB and get their states in the MySQL database.
${'nomR'.$i.$b} = ${'nomR'.$i};
$req = "SELECT * FROM states_log WHERE dev='R$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateR'.$i.$b} = $state;
if ( ${'stateR'.$i.$b} == "1" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/toggle_1.png height=28></a>";
}
else if ( ${'stateR'.$i.$b} == "0" )
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=SR$i target=empty> <img src=img/toggle_0.png height=28></a>";
}
else
{
${'img_linkR'.$i.$b} = "<a href=set_states.php?ip=${'ip'.$b}&cmd=CR$i target=empty> <img src=img/LED_yellow.png height=28></a>";
}
//We set Inputs names for each IPLAB and get their states in the MySQL database.
${'nomI'.$i.$b} = ${'nomI'.$i};
${'multI'.$i.$b} = ${'multI'.$i};
${'img_onI'.$i.$b} = ${'img_onI'.$i};
${'img_offI'.$i.$b} = ${'img_offI'.$i};
${'img_naI'.$i.$b} = ${'img_naI'.$i};
$req = "SELECT * FROM states_log WHERE dev='I$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateI'.$i.$b} = $state;
if ( ${'stateI'.$i.$b} == "1" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_onI'.$i.$b} height=28>";
}
else if ( ${'stateI'.$i.$b} == "0" )
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_offI'.$i.$b} height=28>";
}
else
{
${'img_linkI'.$i.$b} = "<img src=img/${'img_naI'.$i.$b} height=28>";
}
// We check for how many times, the Inputs has changed state to 1, and we set them as a variable for counter.
$req = "SELECT count(*) FROM states_log WHERE dev='I$i' AND state='1' AND mac='${'mac'.$b}'";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
list (${'countI'.$i.$b}) = mysql_fetch_row ($result2);
if (isset(${'multI'.$i.$b}))
{
${'countI'.$i.$b} = ${'countI'.$i.$b} * ${'multI'.$i.$b};
}
}
//We set Analog names fir each IPLAB and get their states in the MySQL database.
for ($i=1; $i <= "3"; $i++ )
{
${'nomA'.$i.$b} = ${'nomA'.$i};
${'unitA'.$i.$b} = ${'unitA'.$i};
$req = "SELECT * FROM states_log WHERE dev='A$i' AND mac='${'mac'.$b}' ORDER BY date_heure DESC LIMIT 1";
$result2 = mysql_query($req);
if(!$result2)
{
die('Query failed: ' . mysql_error());
}
$ligne = mysql_fetch_assoc($result2);
extract($ligne);
${'stateA'.$i.$b} = $state;
}
if ( debug == "1" )
{
echo "${'nom'.$b}<br>";
echo "MAC = ${'mac'.$b}<br>";
for ( $i = 1; $i <= 8; $i++ )
{
echo "${'nomR'.$i.$b} = ${'stateR'.$i.$b}<br>";
echo "${'nomI'.$i.$b} = ${'stateI'.$i.$b}<br>";
}
for ( $i = 1; $i <= 3; $i++ )
{
echo "${'nomA'.$i.$b} = ${'stateA'.$i.$b}<br>";
}
echo "---------------------------------------<br>";
}
$b++;
}
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
if ( debug == "1" )
{
echo 'Page generated in '.$total_time.' seconds.'."\n";
}
mysql_close($con);
?>
I can give access to the source, MySQL etc if someone can help, i am learning right now, And i really enjoy how it goes for now, but the AJAX Jquery thing, i completely miss it!!
Thanx a lot!
You could wright more of an abstract question ... no need for php code ...
If i understood you right , you need to send ajax reqests on a specific time interval to get your updated data ( js function setInterval() )
Here is a link about setInterval : http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
Here is link about ajax : http://www.w3schools.com/ajax/
If this answer has nothing to do with your question , please review it and state what you want to do with your data? Show it on each update? or what kind of update?
You could use javascript to trriger ajax script after 1 sec delay use setTimeout() in javascript for delay And in your php page retrieve the data and echo it.

Categories