MySQL database and importing dates problems - php

Okay,so in my mysql database I use a date field. Using PHP I check if the user is 18 years of age or not. Then I try to enter all the form information to my MySQL database to make a user. I keep getting a blank screen (besides my navbar and footer) The user is not being saved into the database, and the error log shows this error: PHP Recoverable fatal error: Object of class DateTime could not be converted to string in ....
$age = checkAge($_POST["birthday"]);
if($age != false)
{
$ageSuc = "All Good!";
}
else ....
function checkAge ($data)
{
$dateObj = new DateTime($data);
$ageLimit = new DateTime('-18 years');
if ($dateObj > $ageLimit)
{
return false;
}
else
{
$dateObj->format('Y-m-d');
return $dateObj;
}
}
So the question is, do I need to convert the dateTime Obj into a string before MySQL will accept it? The field is set to hold 'dates' so I thought the date obj would be the same thing? How does one change it to a string.

You are returning the DateTime object, because the format function returns a string, it doesn't change the object. Try returning the result of the format function which is the formatted string.
return $dateObj->format('Y-m-d');

$age = checkAge($_POST["birthday"]);
if($age != false)
{
$ageSuc = "All Good!";
}
else ....
function checkAge ($data)
{
$dateObj = new DateTime($data);
$ageLimit = new DateTime('-18 years');
if ($dateObj > $ageLimit)
{
return false;
}
else
{
return $dateObj->format('Y-m-d');
}
}
If you want a string result, you have to return the format() result, not the object itself.
But the error you have specified is not triggered directly in this code, but somewhere in the else, where you try to convert the result to string.

Related

Codeigniter database error handling, trying to cover all of my possible scenarios

I'm trying to cover all my bases in the event my MYSQL database returns any errors (no rows, no connection, no table, etc...) when I'm making a query using CodeIgniter 3.
I have a helper function that returns the latitude and longitude based on a zip code provided. It will always only return a single row (granted the record exits). Here's my helper function as of now:
if (!function_exists('get_coordinates_from_zipcode')) {
//gets latitude and longitude coordinates from supplied zipcode. Returns array
function get_coordinates_from_zipcode($zipcode) {
$ci =& get_instance();
$ci->load->database();
$query = $ci->db->get_where('Geo', array('zip =' => $zipcode))->row_array();
if (!$query) {
return FALSE;
} else {
return $query;
}
}
//* Fields returned from geolocation database *//
/* -zip
-lat
-lng
// Returns false on error or no records
*/
}
And here is my View I'm using (passing $data['array'] array to it from my Controller):
<?php if ($array == FALSE || !$array) : ?>
<?php echo "No data returned"; ?>
<?php else : ?>
<?php echo $array['zip'] . ' is located at ' . $array['lat'] . ' and ' . $array['lng']; ?>
<?php endif; ?>
This works well if there are no rows, but I want to handle any other issues, such as more than one row (highly unlikely to happen), or if there's a problem connecting to the database or table.
I've tried this in my Helper
if ($ci->db->error()) {
return $ci->db->error(); //
} else {
return $query;
}
When I do this, and purposely use an invalid zip code to pass the error to the view, $ci->db->error() always returns array(2) { ["code"]=> int(0) ["message"]=> string(0) "" } and is empty. And of course I get errors that Undefined index: lat and Undefined index: lng
Should I be passing the $ci-db->error() array to the view and acting on it there?
I just want to make sure all my bases are covered. In my mind I should be handling errors in the Helper function but the error() always seems to be empty even when there's an error (such as no rows, or no db connectivity, or no table by that name.
I feel like
if (!$query) {
return FALSE;
} else {
return $query;
}
inside my helper function won't cover all problems I could potentially have connecting to the database.
Why don't you just do the following:
if (!function_exists('get_coordinates_from_zipcode')) {
//gets latitude and longitude coordinates from supplied zipcode. Returns array
function get_coordinates_from_zipcode($zipcode) {
$ci =& get_instance();
$ci->load->database();
if ($ci->db->conn_id === false) {
return false; // connection couldn't be established
}
$query = $ci->db->get_where('Geo', array('zip =' => $zipcode));
if ($query && $query->num_rows() == 1) {
return $query->row_array();
}
return false;
}
//* Fields returned from geolocation database *//
/* -zip
-lat
-lng
// Returns false on error or no records
*/
}
This way:
You test that query didn't return a FALSE result
You test that you are only getting 1 row
You make sure you have established a connection to the db (seems a bit overkill)
Please note: you should always check the value of num_rows() before attempting to access the result array/object. If there are no rows, then you will get undefined indexes when attempting to access the array.
i don't understand the purpose of your helper here - If you dont use a model and if you bypass the controller here why do you even use Codeigniter at first ?
Now your question
if its possible i would create a model where you handle all the errors and try to throw them via Exceptions
a possible approach
Model
class Geo_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_coordinates_from_zipcode($zipcode = false)
{
if (!$zipcode) throw new InvalidArgumentException('Zipcode should be set');
$query = $this->db
->select('*')
->from('Geo')
->where('zip', $zipcode)
->get();
$arrError = $this->db->error();
if (isset($arrError['message']) && !empty($arrError['message'])) throw new RuntimeException($arrError['message']);
if ($query->num_rows() != 1) throw new RuntimeException('Query - Number of rows should be 1');
return $query->row_array();
}
}
controller
class Geo extends CI_Controller
{
public function coordinatesfromzipcode($zipcode)
{
$this->load->model('Geo_model');
try
{
$row = $this->Geo_model->get_coordinates_from_zipcode($zipcode);
//load your coordinates view
}
catch (Excepetion $e)
{
//load an error view or something like that...
echo $e->getMessage();
}
}
}

codeigniter query builder will update db with just about anything

I'm new to codeigniter and trying to get my mind around the query builder functionality. I currently have an update method where I pass user entered data to update a record in the db. I've noticed it seems to be successful no matter what kind of junk data I throw at it, and I'm wondering if there's a setting or something I need to change, or what.
As you can see below, in my model I'm bypassing the user entered value and putting in junk data and it is still successful. It just inserts 0000-00-00. DOB in the DB is a date datatype.
I always get a success result from this, and it updates the DB, so techically it was successful. I have controls in place to prevent junk data from ever being sent to the model, but it doesn't give me warm fuzzies knowing that it is behaving this way.
Controller:
$updateResult = $this->Patients_model->update_patient_profile($this->data['post_data']);
if($updateResult === true)
{
$this->data['patient_profile'] = $this->Patients_model->get_patient_profile($patientId);
$this->data['update_result'] = true;
$this->load->view('index', $this->data);
}
else
{
$this->data['update_result'] = false;
print_r($updateResult);
}
Model:
function update_patient_profile($data)
{
$patient_id = $data['patient_id'];
unset($data['patient_id']);
$data['dob'] = 'this is not even a date'; //will store 0000-00-00 in DB.
$this->db->where('patient_id', $patient_id);
$this->db->update($this->patientsTable, $data);
if($this->db->affected_rows()) {
return true;
}
else
{
return $this->db->error();
}
}
You can check with PHP and thorw an error for invalid date. try this:
function update_patient_profile($data)
{
$patient_id = $data['patient_id'];
unset($data['patient_id']);
$check_date = $data['dob'];
if(strtotime($check_date))
{
$data['dob'] = date("Y-m-d",strtotime($check_date)); // to confirm date is valid and equivalant to database format
}
else
{
throw new Exception("Invalid date", 1);
}
$data['dob'] = 'this is not even a date'; //will store 0000-00-00 in DB.
$this->db->where('patient_id', $patient_id);
$this->db->update($this->patientsTable, $data);
if($this->db->affected_rows()) {
return true;
}
else
{
return $this->db->error();
}
}

PHP check date difference for backward date

I have checked that the input date is a valid date, now need to check for backward date where date_start must be before date_end.
I have tried several other option to no avail, I really dont want to compare the substring of the input if possible.
The input are from html5 date using chrome with format dd/mm/yyyy
class MY_Form_validation extends CI_Form_validation {
public $CI;
public function date_format($date) {
if (($timestamp = strtotime($date)) === false) {
return false;
}
}
//error message stored in caller module language folder
public function backward_date($date_start, $date_end) {
$date_1 = new DateTime($date_start);
$date_2 = new DateTime($date_end);
if ($date_1 > $date_2 == true) {
return false;
}
else {
return true;
}
}
}
try this one
public function backward_date($date_start, $date_end) {
$ts1 = strtotime($date_start);
$ts2 = strtotime($date_end);
$seconds_diff = $ts2 - $ts1;
return ($seconds_diff>0) ? true : false;
}
The problem here is that DateTime is not able to parse the string from 'dd/mm/yyyy' to a valid DateTime Object.
Here is the received error :
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/10/2017)
In order to fix this, you could use the createFromFormat() method from the DateTime model to parse your string with a specified format.
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
So your method would be like :
public function backward_date($date_start, $date_end)
{
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
$date_2 = DateTime::createFromFormat('d/m/Y', $date_end);
return $date_1 <= $date_2;
}
Hope it helps.
Try to this ... Working for me.
function date_calculate($start_date, $end_date) {
$dStart = new DateTime($start_date);
$dEnd = new DateTime($end_date);
$days=0;
if ($dStart < $dEnd) {
$dDiff = $dStart->diff($dEnd);
$dDiff->format('%R');
$days = $dDiff->days;
return $days;
} else {
return $days;
}
}

Function unserialize offset error

I'm building a multilanguage website with Laravel4.
In the database i have column named "content" that contains serialized values for multiple languages. For example:
a:3:{s:2:"gb";s:15:"This is English";s:2:"es";s:5:"Hola!";s:2:"si";s:19:"Slovenija je zakon!";}
The serialized array contains of:
Language abbreviation, taken from Session
Content that comes from the input field
Now when I add new language to the database it creates new serialized string. Great!
But when I want to unserialize that string and add a value into it, i get the following error:
unserialize() [<a href='function.unserialize'>function.unserialize</a>]: Error at offset 0 of 30 bytes
Any ideas what is going on? I understand the meaning of the error, but it just makes no sense, since I'm sure that value in the database is serialized string.
public function setContentAttribute($value)
{
$lang = (Session::has('my.locale') ? Session::get('my.locale') : Config::get('app.locale'));
/* Create new serialized string */
if(empty($this->content)) {
$data[$lang] = $value['content'];
$this->attributes['content'] = serialize($data);
/* Update values */
} else {
$data = $this->content;
$data = unserialize($data)
$data[$lang] = $value['content'];
$this->attributes['content'] = serialize($data);
}
}
P.S: I'm using mutators for adding values to database.
I hope it's clear enough. If there is anything unclear, please comment and I'll fix it.
Thanks!
Ok, I've managed to fix it. I was unserializing my code twice - once in the accessor and once in the mutator. Here is a working example:
public function getVsebinaAttribute($value)
{
$data = unserialize($value);
$lang = $this->getLang();
if (!empty($data[$lang])) {
return $data[$lang];
} else {
return '# Value has not yet been added';
}
}
public function setVsebinaAttribute($value)
{
if (isset($this->attributes['vsebina'])) {
$data = unserialize($this->attributes['vsebina']);
} else {
$data = array();
}
$lang = $this->getLang();
$data[$lang] = $value;
$this->attributes['vsebina'] = serialize($data);
}
protected function getLang()
{
return Session::has('my.locale') ? Session::get('my.locale') : Config::get('app.locale');
}

How to check if todays date is same as a given date in PHP

I am trying to check if today's date is = 04/01/2013 in a PHP file.
I have written the following JS Script.
But I am getting some error. Dont know why.
Please help
//This function will return if today is the date that we are looking for
function isToday($time) // midnight second
{
alert('1');
return (strtotime($time) === strtotime('today'));
}
Testing using the following:
if (isToday('2013-04-01 00:00:00.0') )
{
alert('Yes true');
}
else
{
alert("No false');
}
Please help how to compare today date = 04/01/2013. Thanks.
If you want to do a date/time compare in JavaScript, you will be best off checking this question asked previously:
Javascript equivalent of php's strtotime()?
That is a strtotime equivalent in JavaScript.
Here's a brief example:
var d = new Date("2013-04-01");
if(d == new Date()) {
alert('yes')
} else {
alert('no')
}
In PHP:
// Get the time
$serverDate = date('d/m/Y',time());
// Date to check against
$dateToCheck = '04/01/2013';
if($dateToCheck == $serverDate) {
alert('Yes true');
} else {
alert('No false');
}

Categories