Cannot save a DateTime object to a datetime field in MySQL - php

Here is my database schema for my MySQL database:
create table noticia
(
id int,
imagen varchar(255),
fecha datetime,
titulo varchar(255),
url varchar(255),
descripcion varchar(255),
contenido text
)
I'm using RedBeanPHP as my ORM to save the information to a database. Here is where I'm scraping and parsing the dates to a DateTime object as per the documentation.
foreach ($element->find('span.fechanoticia') as $fecha) {
$tmp = str_replace("/", "-", $fecha->innertext);
print_r($tmp);
$dateFoo = new DateTime($tmp);
echo $dateFoo->format('Y-m-d H:i:s');
$newItem->set_fechanoticia($dateFoo);
}
The $tmp variable this value for example:
05-09-2012
The echo call to format returns:
2012-09-05 00:00:00
Everything is peachy, and working.
However when I try to save it to the database using RedBeanPHP I get this error:
Fatal error: Uncaught exception 'RedBean_Exception_Security' with
message 'Invalid Bean: property fecha ' in
C:\xampp\htdocs\blog-uvm\rb.php:4880 Stack trace: #0
C:\xampp\htdocs\blog-uvm\rb.php(5108):
RedBean_OODB->check(Object(RedBean_OODBBean)) #1
C:\xampp\htdocs\blog-uvm\rb.php(5082):
RedBean_OODB->storeBean(Object(RedBean_OODBBean)) #2
C:\xampp\htdocs\blog-uvm\rb.php(7005):
RedBean_OODB->store(Object(RedBean_OODBBean)) #3
C:\xampp\htdocs\blog-uvm\index.php(60):
RedBean_Facade::store(Object(RedBean_OODBBean)) #4 {main} thrown in
C:\xampp\htdocs\blog-uvm\rb.php on line 4880
Can RedBeanPHP not handle datetime objects?

As per RedBean's documentation (More data types), you can only save DateTime objects if they are in string form.
For example:
// It's a string - not a DateTime.
$photo->created = '1995-12-05 19:00:00';
In this case the solution should be to save the formatted string, not the DateTime object itself:
$newItem->set_fechanoticia($dateFoo->format('Y-m-d H:i:s'));

found this: http://groups.google.com/group/redbeanorm/browse_thread/thread/6961ac635e6886f6
The Optimizer will now convert columns with datetime values to datetimefields. If a different value is inserted the column will be reverted by OODB in fluid mode.

Related

How to use user provided dates with yii db expression

I am sending a user provided date in the format MM/DD/YYYY. Example 10/07/2020. I want to store this date in a column of type TIMESTAMP(0) in an oracle database.
I have this in my code:
$medicalClaimDetail = new MedicalClaimDetail();
$medicalClaimDetail->TREATMENT_DATE = new yii\db\Expression('10/07/2020');
$medicalClaimDetail->save();
However I get this exception:
Error Code : 932 Error Message : ORA-00932: inconsistent datatypes: expected TIMESTAMP got NUMBER Position
using strings worked for me.
in db component config i had:
'on afterOpen' => function($event) {
$event->sender->createCommand("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'")->execute();
$event->sender->createCommand("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'")->execute();
}
in code i set dates and timestamps as strings:
$medicalClaimDetail->TREATMENT_DATE = date('Y-m-d H:i:s', time());
$medicalClaimDetail->save();

How to create solr document with String type using solarium query

I' creating solr document via solarium plugin in php.
But the all document is stored text_general data type except id field. text_general is the default datatype in solr system.
My doubt is why id field is only to stored string type as default.
And If any possible to add document with string type using solarium plugin.
My code part is here,
public function updateQuery() {
$update = $this->client2->createUpdate();
// create a new document for the data
$doc1 = $update->createDocument();
// $doc1->id = 123;
$doc1->name = 'value123';
$doc1->price = 364;
// and a second one
$doc2 = $update->createDocument();
// $doc2->id = 124;
$doc2->name = 'value124';
$doc2->price = 340;
// add the documents and a commit command to the update query
$update->addDocuments(array($doc1, $doc2));
$update->addCommit();
// this executes the query and returns the result
$result = $this->client2->update($update);
echo '<b>Update query executed</b><br/>';
echo 'Query status: ' . $result->getStatus(). '<br/>';
echo 'Query time: ' . $result->getQueryTime();
}
The result document for the above code is here,
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"q":"*:*",
"_":"1562736411330"}},
"response":{"numFound":2,"start":0,"docs":[
{
"name":["value123"],
"price":[364],
"id":"873dfec0-4f9b-4d16-9579-a4d5be8fee85",
"_version_":1638647891775979520},
{
"name":["value124"],
"price":[340],
"id":"7228e92d-5ee6-4a09-bf12-78e24bdfa52a",
"_version_":1638647892102086656}]
}}
This depends on the field type defined in the schema for your Solr installation. It does not have anything to do with how you're sending data through Solarium.
In the schemaless mode, the id field is always set as a string, since a unique field can't be tokenized (well, it can, but it'll give weird, non-obvious errors).
In your case i'd suggest defining the price field as an integer/long field (if it's integers all the way) and the name field as a string field. Be aware that string fields only generate hits on exact matches, so in your case you'd have to search for value124 with exact casing to get a hit.
You can also adjust the multiValued property of the field when you define the fields explicitly. That way you get only the string back in the JSON structure instead of an array containing the string.

Date POST switching types

I don't know really how to elaborate on this problem. I have the following markup in my form:
<input class="form-control" type="date" name="renewal" required="required" id="renewal" />
and if I call var_dump it tells me that it is a String value of the date formatted in a Y-m-d format. However, if I attempt to convert the String to a DateTime object using the following:
$_POST['renewal'] = new DateTime($_POST['renewal']);
I get the following error message:
Fatal error: Uncaught TypeError: DateTime::__construct() expects parameter 1 to be string, object given in *.php:212 Stack trace: #0 *.php(212): DateTime->__construct(Object(DateTime)) #1 {main} thrown in *.php on line 212
So if I try to explicitly convert $_POST['renewal'] to a String using strval:
$_POST['renewal'] = new DateTime(strval($_POST['renewal']));
I receive the following error:
Recoverable fatal error: Object of class DateTime could not be converted to string in *.php on line 212
And if I try to get the format from $_POST['renewal'] using:
$_POST['renewal'] = new DateTime($_POST['renewal']->format('Y-m-d'));
I receive the following error:
Fatal error: Uncaught Error: Call to a member function format() on string in *.php:212 Stack trace: #0 {main} thrown in *.php on line 212
And if I try to not do anything to the POST value and try to set the date's year to this year's value using the following:
$_POST['renewal'] = new DateTime($today->format('Y') . $_POST['renewal']->format('-m-d'));
I receive the same call to a member function error as shown above. So why does it tell me when I attempt to convert the POST value to a DateTime object that it expects a String and not a DateTime object, but whenever I try to use the value as a DateTime object it says that the object is a String?
UPDATE
To show you what I'm trying to do, I am trying to see if the value of $_POST['renewal'] is greater than today's date. If the value of the POST greater than today's date then I'm changing the value to today's year and if the value is still not greater than today's date then I'm also adding 6 month's to the date. Here is the code that I'm trying to use:
$today = new DateTime("now");
$_POST['renewal'] = new DateTime($_POST['renewal']->format('Y-m-d'));
if ($_POST['renewal'] < $today) {
$_POST['renewal'] = new DateTime($today->format('Y') . $_POST['renewal']->format('-m-d'));
if ($_POST['renewal'] < $today) {
date_add($_POST['renewal'], date_interval_create_from_date_string('6 months'));
}
}
The value that I'm using to test the code is 2016-06-28, and what I expect it to do is change to 2018-06-28 and then again to 2018-12-28. But if I send the value of 2017-11-01 then it would change to 2018-11-01 and if I send the value of 2018-12-01 then it would not change at all.

PHP Uncaught exception when trying to get the first row of an Excel table

I have a Excel table and I'm using PHPExcel to read and display it. And now I want to get the first row. So here's my code:
$column = ord($sheet->getHighestColumn())-64;
for($i = 0; i<$column; $i++){
echo $sheet->getCellByColumnAndRow($i,1) . ' ';
}
And this is what I get:
country_code country_name Nom du pays modification_flag tag Code ISO Alphabétique 2 positions Iban O/N
So I have 7 columns and the output is correct but I also have an fatal error
Fatal error: Uncaught exception 'PHPExcel_Exception' with message 'Invalid cell coordinate [AA1' in /Library/WebServer/Documents/BICIBAN/PHPExcel-1.8/Classes/PHPExcel/Cell.php:594 Stack trace: #0 /Library/WebServer/Documents/BICIBAN/PHPExcel-1.8/Classes/PHPExcel/Worksheet.php(1218): PHPExcel_Cell::coordinateFromString('[AA1') #1 /Library/WebServer/Documents/BICIBAN/PHPExcel-1.8/Classes/PHPExcel/Worksheet.php(1200): PHPExcel_Worksheet->createNewCell('[AA1') #2 /Library/WebServer/Documents/BICIBAN/lecture.php(112): PHPExcel_Worksheet->getCellByColumnAndRow(18278, 1) #3 {main} thrown in /Library/WebServer/Documents/BICIBAN/PHPExcel-1.8/Classes/PHPExcel/Cell.php on line 594
I may know what it is trying to say, when I have many columns and I have for instance the AA column. So I did a function that can convert until the ZZ column but that does not correct my fatal error.
Thanks for your help
Oh, I just found what is wrong... I just forgot a $ in my for loop
for($i = 0; $i<$column; $i++){
FeelsBadMan :(

datetime datatype not working in soap php

This is my code
$c = new soapclient('http://www.redbus.in/WS2/BookingService.asmx?wsdl',
array('authentication' => array('LoginID' => 'x','Password'=>'x')));
$timezone = new DateTimeZone('UTC');
$time='2012-04-17T16:50:45';
$date = new DateTime($time,$timezone);
$sourceid=array('SourceID'=>'244','DestinationID'=>'477','DateOfJourney' =>$date);
$stockprice = $c->GetAvailableRoutes($sourceid);
print_r($stockprint);
it's not working in datetime format datatype variable
it shows error like this
Fatal error: Uncaught SoapFault exception: [soap:Client] Server was unable to read request. ---> There is an error in XML document (2, 252). ---> The string '' is not a valid AllXsd value. in E:\xampplite\htdocs\index1.php:9 Stack trace: #0 [internal function]: SoapClient->__call('GetAvailableRou...', Array) #1 E:\xampplite\htdocs\index1.php(9): SoapClient->GetAvailableRoutes(Array) #2 {main} thrown in E:\xampplite\htdocs\index1.php on line 9
I had a similar problem when using a SOAP service from PHP. I fixed it using:
$date->format('c');
(ISO 8601 date, added in PHP 5, looks like: 2004-02-12T15:19:21+00:00)
You need to format it, otherwise you are throwing an DateTime object into your array (which PHP tries to convert to a string, which does not work)
For example:
$date->format('Y.m.d H:i:s');
Usage
$sourceid = array('SourceID'=>'244','DestinationID'=>'477','DateOfJourney' => $date->format('Y.m.d H:i:s'));

Categories