There were some problems with symfony over time. unfortunately, this is not the first time I have run into this. Has anyone ever encountered this problem? If so, thank you for your help.
Controller.php
if($xml = simplexml_load_file($feedUrl)) {
$result["chanel"] = $xml->xpath("/rss/channel/item");
foreach($result as $key => $attribute) {
$i=0;
foreach($attribute as $element) {
$ret[$i]['title'] = (string)$element->title;
$ret[$i]['category'] = (string)$element->category;
$ret[$i]['link'] = (string)$element->link;
$ret[$i]['pubDate'] = json_decode(json_encode($element->pubDate), TRUE);
$ret[$i]['enclosure'] = (array)$element->enclosure;
$ret[$i]['description'] = (string)$element->description;
$i++;
}
}
}
foreach ($ret as $feed){
$newnews = new Newsfeed();
$newnews->setTitle($feed['title']);
$newnews->setCategory($feed['category']);
$newnews->setLink($feed['link']);
$newnews->setDescription($feed['description']);
$newnews->setDate(date("Y-m-d h:i:sa", strtotime($feed['pubDate'][0])));
$newnews->setImage($feed['enclosure']['#attributes']['url']);
$newnews->setSource('2');
$entityManager->persist($newnews);
$entityManager->flush();
}
This problem
The date() function returns a string, so this line won't work:
$newnews->setDate(date("Y-m-d h:i:sa", strtotime($feed['pubDate'][0])));
You can probably just use:
$newnews->setDate(new \DateTimeImmutable($feed['pubDate'][0]));
I have had this problem before. For me, when working with only Dates (no time) it was kind of misleading the fact that MySQL and thus doctrine annotations have the Date type, but PHP/Symfony does not.
As mentioned by Chris, the date() function returns a string, but the class DateTime is your friend here.
Even when it is called DateTime, this class allows formatting and you can indeed, for example, retrieve only a date with it. An example would be:
$date = new DateTime('2000-01-01 12:30:25');
echo $date->format('Y-m-d');
Or in your case, in which you DO want to return the time part too:
$pubDate = new DateTime($feed['pubDate'][0])->format('Y-m-d h:i:sa');
$newnews->setDate($pubDate);
Which can be easily transformed into a one-liner.
This will show only what you ask for in the format() function.
There is one trickiness though. In my country at least, it is very common to format dates with a slash (/), but DateTime->format() will not work with Y/m/d, so keep it in mind and check for the correct format here if you are going to be using slashes.
Related
$this['order'] = $order = \Spot\Shipment\Models\Order::find($this->param('id'));
$progress = 0;
$progress_status = 'warning';
$shipdate = \Carbon\Carbon::parse($order->ship_date);
$deliverydate = (($order->deliverytime)? $shipdate->addHours($order->deliverytime->count) :null);
$today = \Carbon\Carbon::now();
$time_diff = $today->diffInDays($deliverydate, false);
switch($order->requested){
simply put $order is most likely null. Work out why, dump the value of $this->param('id'), it might be null too.
now, some little tips:
use a naming convention for your variables, you are mixing snake_case and nocase.
what is $this['order'], some ArrayAccess implementation? And why not $this->order?
learn more at phptherightway.com
Also as you are new to StackOverflow, please take some time to write out a more thought out question detailing what is going wrong and provide some context.
Also, think about tags, for example, this question has nothing to do with mysql and phpmyadmin, correct?
I am 2 days into learning PHP and frustratingly I am struggling to GET and use a parameter passed into my API.
I have read the PHP $_GET documentation, it didn't take long, and also a number of SO pages about $_GET.
My use case is simple. I want to retrieve a list of records from MySQL db if they have a modified date greater than the passed in date. The function works if I hard code '2019-03-18 00:00:01' for example.
Using echo I can see I am getting the parameter.
In fact, copying the output from echo and using to update the function which I use in the argument returns the expected result.
I'm guessing this has been asked before but I can't find it. All the examples I read seem more challenging i.e. multiple variables or challenges with the function etc.
I must have made a newb mistake somewhere.
<?php
//Returns Lab Results Modified after the passed in date
include_once 'db_functions.php';
$db = new DB_Functions();
//Get JSON posted by Android Application
if (isset($_GET['date'])) {
$json = $_GET['date'];
echo $json;
// commenting out the next two line results in
// '2019-03-19 00:00:01' returning and not the json array.
$json = '2019-03-18 00:00:01';
echo $json;
$mod = $db->getLabResultsModifiedAfter($json);
$a = array();
$b = array();
if ($mod != false){
while ($row = mysqli_fetch_array($mod)) {
$b["ID"] = $row["ID"];
$b["last_modified"] = $row["last_modified"];
$b["LabRef"] = $row["LabRef"];
array_push($a,$b);
}
echo json_encode($a);
}
} else {
// Fallback behaviour goes here
}
?>
I haven't developed the app side function yet. I am using postman to pass in date of '2019-03-18 00:00:01' i.e. this for local.
Answer as provided by #aisby. I was using quotes in the passed in parameter.
The date you are passing in your URL does not following the format
'2019-03-18 00:00:01'. Try navigating to this URL ...
localhost:8080/its/… ... I have URL encoded the date 2019-03-18
00:00:01 in the querystring. I can see that you comment shows a date
query string starting with %27 which is the URL encoded single quote.
You should only send the value in query string variables. Not the
single or double quote string delimiters. – asiby 18 hours ago
I'm working on a website in php with the laravel framework and I have a database in phpmyadmin, I have a form and 2 inputs of type datetime-local, when I select the datetime from the inputs and then I send the form I get this error.
The datetime data that I would like to insert into my Table of my database in that's error, it's:
26, 2018-10-11T05:00, 2018-10-12T05:00. That's letter 'T' I think it's was me bring problems. Is possible to change that letter to a blank space? Possibly using javascript, o before the function store() of my Controller save the record in my database, can do something to save the datetime data from the inputs.
I put the code of the function store()
public function store(Request $request){
$hours = new HoursNew();
try {
/*HERE ARE THE NAMES FROM THE INPUTS IN MY FORM,
ALSO THE NAMES OF THE FIELDS OF MY TABLE IN MY DATABASE*/
$hours->id = $request->id;
$hours->time_start = $request->time_start;
$hours->time_end = $request->time_end;
$hours->estate_time_id = $request->estate_time_id;
$hours->court_id = $request->court_id;
$hours->save();
} catch (\Illuminate\Database\QueryException $e) {
Session::flash('error', 'Ups! We have some problems to process your operation');
return redirect()->route('ListHours.store');
}
Session::flash('message', "It's OK");
return redirect()->route('ListHours.store');
}
For each of the Request fields that dont conform to the database datetime requirements you will have to reformat then like this for example
$date = DateTime::createFromFormat('Y-m-d\Th:i', $request->time_start);
$hours->time_start = $date->format('Y-m-d H:i:s');
You could use php DateTime's format function to put it into the correct format:
http://php.net/manual/en/datetime.format.php
Laravel also has Carbon in it by default: https://carbon.nesbot.com/docs/
I normally use Y-m-d H:i:s for my format string, but both of the docs show additional formatting options.
you need to format the date-time
example
edited
$hours->time_start = date('Y-m-d H:i:s', strtotime($request->time_start));
Try to convert the date before calling save() function like this -
$hora_inicio = new DateTime($request->hora_inicio);
$hora_inicio = $hora_inicio->format('Y-m-d h:i:s');
$hora_fin = new DateTime($hora_fin);
$hora_fin = $hora_inicio->format('Y-m-d h:i:s');
and then assign these variables to your object.
I want to validate for a 24 hour format.
The below code accepts 1:05:24 which is wrong, as it should instead only accept 01:05:24
try
{
foreach ($arr as $key=>$item)
{
if (date('H:i:s', strtotime($item[1])))
{
} else {
throw new Exception('Invalid Time Format');
}
}
}
catch (Exception $e)
{
echo $exp = $e->getMessage();
}
The following use of preg_match will differentiate between the two cases you have mentioned.
However, note that neither this nor the method that you mentioned in the question will correctly detect an invalid time such as 00:99:99.
If you require that, you need a different method, the easiest of which is probably to parse out the numbers and run this function on it.
<?php
$mydate_bad = "1:05:70";
$mydate_good = "01:05:24";
print (preg_match("/^\d\d:\d\d:\d\d$/", $mydate_bad)); # Returns 0
print (preg_match("/^\d\d:\d\d:\d\d$/", $mydate_good)); # Returns 1
?>
Based on the code you've provided, one way would be the following:
$php_date = date('H:i:s', strtotime($item[1]));
if ($php_date && $php_date == $item[1]) {
// valid date
}
This will check that a date could be created as in your code, and it will also ensure that the resulting date in the format H:i:s corresponds to what the user entered.
However, in terms of user-friendliness, if you can create a date from the user input, it might be better just to accept it and add the leading 0 yourself if it is missing. Simply use $php_date in favor of $item[1] afterwards.
I populate a list of dates from a MySQLdatabase like this:
<?php
while ($row = mysql_fetch_array($list_customers)) {
echo "<tr>\n";
echo "<td>".$row['customer_date']."</td>\n";
echo "</tr>\n";
}
?>
Now I would like to add the result inside a <span> that changes class='' based on some criteria:
If date result is within a 30 days reach from todays date, add
class='yellow'
If date result is over 30 days from today, add class='green'
If date result has passed, based on todays date, add class='red'
Would this be possible? Thanks in advance.
Yes it is. Just compare your date with current time using a series of if statements and assign a variable to the class name, like this:
while ($row = mysql_fetch_query($list_customers)) {
echo "<tr>\n";
$class = "class='green'";
if (strtotime($row['customer_date']) < time()) {
$class = "class='red'";
}elseif (strtotime($row['customer_date']) < time() + 30*24*3600) {
$class = "class='yellow'";
}
echo "<td><span $class>" . $row['customer_date'] . "</span></td>\n";
echo "</tr>\n";
}
It's really just a simple case of writing the if() conditions you specified. There's no magic to it.
Firstly, we need to know what format your customer_date field is in. Since you're printing it directly into the HTML code I guess it's in a text format, so the first thing we need to do is convert it to a date object.
$custDate = new DateTime($row['customer_date']);
This will only work if the date is in a suitable format, but to be honest if it isn't in standard MySQL date format then you should stop now and fix that before we go any further.
You'll also need the current date as a date object:
$currDate = new DateTime();
Now you can compare them easily enough using the methods on the DateTime class:
$dateDiff = $currDate->diff($custDate)->days;
Now you've got that, you can just do your if() conditions.
However, I would note a few things:
You're using mysql_fetch_array(). Please note that the mysql_ functions are considered obsolete; you should replace with mysqli_xxx or the PDO library wherever possible.
You suggest putting the class into a <span> inside the <td> -- it is possible to put the class directly into the <td>. This would be a cleaner option, so I'll use that in the answer, though it is up to you.
You suggest using class names red, green, yellow. Please note that this is not a particularly good use of class names. Class names should reflect what the element is actually for, rather than how it looks. This is because the whole point of using classes and separating the styles away from the HTML is so that the styles can be changed without needing to alter the HTML. But if the class names are just colour names, it ties it logically to that colour; you may just as well put the colours directly into the HTML. Better choices of class name would perhaps be something like custExpired, custNearlyExpired, etc. That would give you more flexibility later, and make the code easier to understand for anyone reading it (eg the google bot!).
So with all that in mind, here's some code for you:
$currDate = new DateTime();
while ($row = $mysqli->fetch_array($list_customers)) {
$custDate = new DateTime($row['customer_date']);
$dateDiff = $currDate->diff($custDate)->days;
$class = '';
if($dateDiff < 30) { $class = 'custNearlyExpired'; }
if($dateDiff < 0) { $class = 'custExpired'; }
echo "<td class='custDate {$class}>{$row['customer_date']}</td>\n";
}
and CSS:
td.custDate {
background: green;
}
td.custDate.custNearlyExpired {
background: yellow;
}
td.custDate.custExpired {
background: red;
}
Hope that helps.