Validating Date of birth using data from API call - php

I'm adding date of birth validation to my Twilio flow. Format is mm/dd/yyyy. So user would input 01021999 for Date of Birth: 01-02-1999.
I pass the input as a parameter to my validation script (PHP) on my VPS via and http request.
The problem is that if I manually set the $dob variable in my script it works, but if I pull that info from twilio there's an issue and the http request sends an error.
I know php treats numbers leading with zeros different and you have to pass them as strings. Tried using strval() to the dob variable to be able to use the input but haven't had any luck.
Works:
$account_number = 1234;
$dob = "01021999";
$dob_length = strlen($dob);
if ($dob_length = 8) {
echo $dob_month = substr($dob, 0, 2);
echo $dob_day = substr($dob, 2,2);
echo $dob_year = substr($dob, 4, 4);
echo $dob_full = $dob_month . "-" . $dob_day . "-" . $dob_year;
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '".$account_number."' AND Guar_DOB LIKE '%".$dob_full."%' ";
$rows = getRows($sql1);
Doesn't work (with or without turning the $dob to a string using strval() :
require_once('logs.php');
require_once('db.php');
require_once('rest.php');
$data = $_REQUEST;
start_log();
$filename = basename(__FILE__);
echo "<pre>".print_r($data,true)."</pre>";
end_log();
header("Content-Type: application/json; charset=UTF-8");
$rfields = explode(",","client_id,account_number,dob");
foreach($rfields as $rf){
if(!isset($data[$rf])){
$message = $rf." is required.";
$status = "error";
echo json_encode(compact('status','message')); die();
}
}
extract($data);
$dob_str = strval($dob);
$dob_length = strlen($dob_string);
if ($dob_length = 8) {
echo $dob_month = substr($dob_str, 0, 2);
echo $dob_day = substr($dob_str, 2,2);
echo $dob_year = substr($dob_str, 4, 4);
echo $dob_full = $dob_month . "-" . $dob_day . "-" . $dob_year;
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '".$account_number."' AND Guar_DOB LIKE '%".$dob_full."%' ";
$rows = getRows($sql1);
}

Try this
$dob = '01021999';
$account_number = 'whatever';
if (validateDate((string)$dob, 'dmY')) {
$date = DateTime::createFromFormat('dmY', $dob);
$final_date = $date->format('Y-m-d');
$sql1 = "SELECT * FROM accounts WHERE Acct_Nbr = '" . $account_number . "' AND Guar_DOB LIKE '%" . $final_date . "%' ";
$rows = getRows($sql1);
}
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}

Related

Data from PDO query returning nothing - Suddenly stopped working

unsure why this is not working, suddenly stopped working today randomly.
$row is returning nothing for some reason and when I try to format the date I get an error as its not valid.
Any help appreciated.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM notifications");
$stmt->execute();
$result = $stmt -> fetchAll();
foreach( $result as $row ) {
$recipient = $row['recipient'];
$day = $row['day'];
$month = $row['month'];
$year = $row['year'];
$hour = $row['hour'];
$minute = $row['minute'];
//Now we need to convert the times for this row into meaningful data
$date = $day . "." . $month . "." . $year . " " . $hour . ":" . $minute . ":45";
echo "<br/><br/>";
echo "Date: " . $date;
$dateObject = DateTime::createFromFormat('d.m.Y H:i:s', $date);
$formattedDate = $dateObject->format('Y-m-d H:i:s');
//Get current time
$currentDate = new DateTime("now", new DateTimeZone('Australia/Perth'));
$currentDate = $currentDate->format('Y-m-d H:i:s');
//Now we have current date and time, as well as date and time from table of db.
//Lets compare the times.
if ($formattedDate < $currentDate) {
//License expired
sendPushNotifcation($recipient);
$stmt = $conn->prepare("DELETE FROM notifications WHERE `recipient` ='".$recipient."'");
$stmt->execute();
}
}

Appointment Booking System Slots

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)

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."'";

Format Date in PHP m/d/y to Y-m-d?

I am trying to format a date string i rip from the web the date comes in as m/d/y and I need to insert it into MYSQL currently I get an error PHP Fatal error: Call to a member function format() on a non-object
Code:
<?php
include 'ganon.php';
$id = array(8573, 53816, 7746, 80748, 7714);
for($l=0; $l<sizeof($id); $l++) {
$html = file_get_dom("http://pregame.com/pregamepros/pro-bettor/picks.aspx?id=" . $id[$l]);
$picks = $html('div[class="div-table-col"]');
$array = array();
$j =0;
for($i=0; $i<sizeof($picks); $i+=8) {
$array[$j] = array("date" => trim($picks[$i]->getPlainText()),
"sport" => trim($picks[$i+1]->getPlainText()),
"pick" => trim($picks[$i+2]->getPlainText()),
"score" => trim($picks[$i+3]->getPlainText()),
"odds" => trim($picks[$i+4]->getPlainText()),
"size" => preg_replace('/\$/', "", $picks[$i+5]->getPlainText()),
"winloss" => trim($picks[$i+6]->getPlainText()),
"money" => (int)preg_replace('/\$/', "", $picks[$i+7]->getPlainText()));
$j++;
}
//enter picks into database
//make sure we do not add picks we already have
$mysqli = new mysqli("host", "user", "pass", "db");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}
if($id[$l] == 8573) {
//$query = "SELECT `date` FROM `db`.`vegasrunner` where date=" . date('Y-m-d');
for($i=0; $i<sizeof($array); $i++) {
$query = "SELECT `date`,`pick` FROM `db`.`vegasrunner` where date=" . "'" . $array[$i]["date"] . "'" . " AND pick=" . "'" . $array[$i]["pick"] . "'";
$result = $mysqli->query($query);
$row = $result->fetch_row();
if(sizeof($row) < 1) {
$result->close();
$date = new DateTime();
$date = DateTime::createFromFormat('m/d/y', $array[$i]["date"]);
//$date = $array[$i]["date"];
$sport = $array[$i]["sport"];
$pick = $array[$i]["pick"];
$score = $array[$i]["score"];
$odds = $array[$i]["odds"];
$size = $array[$i]["size"];
$winloss = $array[$i]["winloss"];
$money = $array[$i]["money"];
echo $date->format('Y-m-d');
$query = "INSERT INTO `db`.`vegasrunner` (`date`, `sport`, `pick`, `score`, `odds`, `size`, `winloss`, `money`) VALUES (" . "'" . $date->format('Y-m-d') . "'" . ", '$sport', '$pick', '$score', '$odds', '$size', '$winloss', '$money')";
$mysqli->query($query);
}
} }
The only plausible explanation I can see is if createFromFormat() is failing, which might happen if the input date isn't in the format you're expecting.
Check that the input string is in the format you think, and alter your code to include a check for failure at the createFromFormat() call.
I ended up writing my own function to parse the date. It turns out there was a hidden space before the month.
function formatDate($date) {
//date = 07/12/13
$date = explode('/', $date);
//for some reason in ubuntu month had a space had to get last 2 characters
$month = substr($date[0], -2);
$day = trim($date[1]);
$year = date('y') == $date[2] ? date('Y') : date('Y');
return $year . "-" . $month . "-" . $day;
}

array_combine usage or query error?

I have never used array_combine before and I am getting a "Boolean instead of resource" error in the query. If I change the query to read ... WHERE cal_id = " . $quidx . "; the Boolean error goes away but I get unexpected T_STRING errors later in the script for reasons I can't figure, and the outcome of the query is nothing.
Main question: Is this the proper usage for array_combine? If so, what am I missing in the rest of this script that causes no information after the query? $quid1 is an array of id numbers and $tm is an array of Unix timestamps. Both arrays check out to have the same number of rows consistently. After array_combine, $cls1 returns a valid array of both previous arrays but they don't seem to work in the query.
Thanks for helping. I'm still learning.
I have edited the script to include the new query statement. Problems now are with the foreach statements where the error reads invalid argument.
$cls1 = array_combine($quid1, $tm);
$quidx = array_values($quid1);
$quclx = array_values($tm);
//// note to self.. start final query for email write with new id data, likely redundant.
$qumail = "SELECT cal_id, cal_name, cal_time, cal_description FROM webcal_entry WHERE cal_id in (" . implode (',' , $quidx) . ")";
$wemail = mysql_query($qumail);
while ($row = mysql_fetch_array($wemail, MYSQL_NUM)) {
$quname2 = $row[1];
$qtime = $row[2]
$qudesc2 = $row[3];
Here's the complete script section where this is applicable. I'm still pecking through it so it's not all fixed yet:
$cls1 = array_combine($quid1, $tm);
$quidx = array_values($quid1);
$quclx = array_values($tm);
//// note to self.. start final query for email write with new id data, likely redundant.
$qumail = "SELECT cal_id, cal_name, cal_time, cal_description FROM webcal_entry WHERE cal_id in (" . implode (',' , $quidx) . ")";
$wemail = mysql_query($qumail);
while ($row = mysql_fetch_array($wemail, MYSQL_NUM)) {
$quname2 = $row[1];
$qtime = $row[2]
$qudesc2 = $row[3];
}
foreach ($qtime as $key=>$btUx) {
if (strlen($btUx) < 6){
$btUx = '0' . $btUx;
date_default_timezone_set('UTC');
$unixEpoch = strtotime($btUx);
date_default_timezone_set('America/Denver');
$formtime = date("H:i", $unixEpoch);
}
}
foreach ($tm as $key=>$tf) {
$idnotime = 0;
$idnow = (strlen($tf) > 2);
switch($tf) {
case $idnow:
$repmlnow = sprintf("Event: %s \nTime: %s \nDesc: %s \n\n", $row[1], $formtime, $row[3]);
break;
case $idnotime:
$repmlnotm = sprintf("Event: %s \nDesc: %s \n\n", $row[1], $row[3]);
break;
}
}
/////===================== send mail...
This is my last edit unless there are other comments. I have changed the original script to the following and everything seems to work properly in this case thanks to the contributor below...
$cls1 = array_combine($quid1, $tm);
$quidx = array_values($quid1);
$quclx = array_values($tm);
$qumail = "SELECT cal_id, cal_name, cal_time, cal_description FROM webcal_entry WHERE cal_id in (" . implode (',' , $quidx) . ")";
$wemail = mysql_query($qumail);
while ($row = mysql_fetch_array($wemail, MYSQL_NUM)) {
$quname2 = $row[1];
$qtime = $row[2];
$qudesc2 = $row[3];
}
if(strlen($qtime) < 6){
$btUx = '0' . $qtime;
date_default_timezone_set('UTC');
$unixEpoch = strtotime($btUx);
date_default_timezone_set('America/Denver');
$formtime = date("H:i", $unixEpoch);
}elseif(strlen($qtime) > 5){
date_default_timezone_set('UTC');
$unixEpoch = strtotime($value);
date_default_timezone_set('America/Denver');
$formtime = date("H:i", $unixEpoch);
}
foreach ($quclx as $key=>$tf) {
$idnotime = 0;
$idnow = (strlen($tf) > 2);
switch($tf) {
case $idnow:
$repmlnow = sprintf("Event: %s \nTime: %s \nDesc: %s \n\n", $quname2, $formtime, $qudesc2);
break;
case $idnotime:
$repmlnotm = sprintf("Event: %s \nDesc: %s \n\n", $quname2, $qudesc2);
break;
}
}
/////===================== send mail...
$quidx is an array with numerical index as key and $quid1 array values as it value. try change query become:
$qumail = "SELECT cal_id, cal_name, cal_time, cal_description FROM webcal_entry WHERE cal_id in (" . implode (',' , $quidx) . ")";

Categories