String datetime insert into mysql database with codeigniter - php

I am having following MySQL table
EventId ObjectKey Title Description When Duration Where Status
INT CHAR(36) VARCHAR(500) VARCHAR(8000) DATETIME VARCHAR(500) VARCHAR(500) TINYINT
and my PHP array is
$data = array(
'Title' => $title,
'Description' => $description,
'When' => $when,
'Duration' => $duration,
'Where' => $where
);
The variable $when contains 02/21/2013. When I try to insert to the table with CodeIgniter
public function insert_event($guid, $data)
{
$CI = & get_instance();
$CI->load->database('default');
$CI->db->set($data);
$CI->db->set('ObjectKey', $guid);
$CI->db->set('Status', 1);
$vari = $CI->db->insert('Events');
return $vari;
}
Everything inserted correctly except date. Can you help me on this?

Use the correct MYSQL format for the date YYYY-MM-DD. For example change this in your code:
$data = array(
'Title' => $title,
'Description' => $description,
'When' => date('Y-m-d', strtotime($when)),
'Duration' => $duration,
'Where' => $where
);

Dates in mySQL are YYYY-MM-DD
You are inserting a date MM/DD/YYYY
So try this:
$data = array(
'Title' => $title,
'Description' => $description,
'When' => date('Y-m-d', strtotime($when)),
'Duration' => $duration,
'Where' => $where
);

Simplest way to store string date in any format in mysql
$srcFormat = "m/d/Y"; //convert string to php date
$destFormat = "Y-m-d" //convert php date to mysql date string
$data = array(
'Title' => $title,
'Description' => $description,
'When' => DateTime::createFromFormat($srcFormat, $when)->format($destFormat),
'Duration' => $duration,
'Where' => $where
);

Related

CakePHP 3: Error while passing an array in URL

I am trying to pass datetime variables into my exportcsv method to generate .csv file with data from indicated time period.
Both variables are associative arrays that look like this:
[
'beginning' => [
'year' => '2016',
'month' => '06',
'day' => '23',
'hour' => '11',
'minute' => '15'
],
'end' => [
'year' => '2016',
'month' => '06',
'day' => '29',
'hour' => '11',
'minute' => '15'
]
]
When I try to pass variables I get an error with this message (yep, I've got the same two warnings):
Warning (2): rawurlencode() expects parameter 1 to be string, array given [CORE\src\Routing\Route\Route.php, line 574]
Warning (2): rawurlencode() expects parameter 1 to be string, array given [CORE\src\Routing\Route\Route.php, line 574]
rawurlencode() is a basic PHP function and this is the line 574:
$pass = implode('/', array_map('rawurlencode', $pass));
It looks like some problem with URL rewriting, but frankly I don't know how to fix it. Any ideas?
exportcsv method in EventsController
public function exportcsv($beginning = null, $end = null)
{
if ($this->request->is('post')) {
$beginning = $this->request->data['Export']['beginning'];
$end = $this->request->data['Export']['end'];
return $this->redirect([$beginning, $end]);
}
if (!$beginning && !$end) {
return $this->render();
}
$this->response->download('export.csv');
$data = $this->Events->find('all')
->select([
'title',
'created',
'description',
'ended',
'working_hours',
'price',
'username' => 'Users.name',
'statusname' => 'Statuses.name',
'employeename' => 'Employees.name'
])
->leftJoinWith('Statuses')
->leftJoinWith('Users')
->leftJoinWith('Employees')
->where(["created BETWEEN " . $beginning . " AND " . $end])
->autoFields(true)
->toArray();
$_serialize = 'data';
$_delimiter = chr(9); //tab
$_extract = ['title', 'created', 'description', 'ended', 'working_hours', 'price', 'username', 'statusname', 'employeename'];
$this->set(compact('data', '_serialize','_delimiter', '_extract'));
$this->viewBuilder()->className('CsvView.Csv');
return;
}
exportcsv.ctp view:
<div class="events form large-6 medium-4 columns content">
<?= $this->Form->create('Export'); ?>
<?= $this->Form->input('beginning', array('type'=>'datetime', 'interval' => 15, 'label' => 'Beginning:')); ?>
<?= $this->Form->input('end', array('type'=>'datetime', 'interval' => 15, 'label' => 'End:')); ?>
<?= $this->Form->button(__('Add')) ?>
<?= $this->Form->end() ?>
</div>
You cannot pass arrays in a URL array, the router doesn't support that. Also you need to additionally pass Instead, convert your single values to proper datetime strings, you could easily do that via the DateTimeType class, something like
if ($this->request->is('post')) {
$beginning = $this->request->data('Export.beginning');
$end = $this->request->data('Export.end');
$type = \Cake\Database\Type::build('datetime');
$beginning = $type->marshal($beginning)->format('Y-m-d H:i:s');
$end = $type->marshal($end)->format('Y-m-d H:i:s');
return $this->redirect([
$beginning,
$end
]);
}
Also, as already mentioned in the comments, you need to fix your where() call, as currently it has an SQL injection vulnerability. The keys of key => value items, as well as value only items, are not going to be bound, but inserted into the query directly!
Cakes expression builder ships with methods to safely generate BETWEEN expressions:
->where(function(\Cake\Database\Expression\QueryExpression $exp) use ($beginning, $end) {
return $exp->between('Events.created', $beginning, $end);
});
See also
API > \Cake\Database\DateTimeType::marshal()
Cookbook > Database Access & ORM > Query Builder > Advanced Conditions
CakePHP 3.0 -> Between find condition
your redirect is wrong
return $this->redirect([
'controller' => 'yourController',
'action' => 'yourAction',
$yourData]
);
see the Cookbook for more information on this topic

how to encode json array from mysql table using php

<?php
$db = new PDO('mysql:host=localhost:3306;dbname=DB1;', 'user1','123456');
$sql = 'SELECT * FROM events';
$out = array();
foreach($db->query($sql) as $row) {
$out[] = array(
'id' => $row->title,
'title' => $row->name,
'url' => $row->url,
'class' => $row->class,
'start' => $row->start . '000',
'end' => $row->end .'000'
);
}
echo json_encode(array('success' => 1, 'result' => $out));
exit;
?>
Table Structure
Field Type Null Key Default Extra
id int(5) NO NULL
title text NO NULL
url text NO NULL
class text NO NULL
start datetime NO NULL
end datetime NO NULL
It displays output as
{"success":1,"result": [{"id":null,"title":null,"url":null,"class":null,"start":"000","end":"000"}, {"id":null,"title":null,"url":null,"class":null,"start":"000","end":"000"}]}
i want to print data in tables instead of null
Thank You.
You are not querying your rows the proper way.
Instead of :
'id' => $row->title,
use
'id' => $row['title'],
for more information, see example 1 in the official documentation
not tried this but you could change this:
foreach($db->query($sql) as $row) {
to
foreach($db->query($sql) as (object)$row) {
... which might allow the syntax used to access records.

ACF Update Field into nested repeater field

I'm trying to let users post from the front end into a nested ACF repeater field.
I've got the sub fields in the first repeater posting fine. But, I can't quite figure out how to get the nested repeater working properly.
Here's the code I have so far:
$event_field_key = 'field_535e6b9ffe3da';
$events[] = array(
'start-date' => $startDate,
'end-date' => $endDate,
'notes' => $_POST['p'.$p.'-notes'],
'start-end-times' => array(
'start-time' => '09:00', // would be dynamic
'end-time' => '17:00' // would be dynamic
)
);
update_field($event_field_key, $events, $post_id);
I'm not sure if I can just nest another array in there, or if I need to do something else.
[UPDATE]
I've just done this and it does input into the first row:
$event_field_key = 'field_535e6b9ffe3da';
$events[] = array(
'start-date' => $startDate,
'end-date' => $endDate,
'notes' => $_POST['p'.$p.'-notes'],
'start-end-times' => array(
'start-time' => '9:00',
'end-time' => ' 17:00'
)
);
update_field($event_field_key, $events, $post_id);
However, this code puts row 1 values both as 9 and row 2 values as 1.
So it looks like:
Row 1: start time: 9, end time: 9
Row 2: start time: 1, end time: 1
I can't seem to find any documentation on this, but it looks like it's possible, just a case of figuring out the syntax.
The fix was an array of arrays:
$event_field_key = 'field_535e6b9ffe3da';
$events[] = array(
'start-date' => $startDate,
'end-date' => $endDate,
'notes' => $_POST['p'.$p.'-notes'],
'start-end-times' => array(
array(
'start-time' => '09:00',
'end-time' => '17:00'
),
array(
'start-time' => '10:00',
'end-time' => '16:00'
)
)
);
update_field($event_field_key, $events, $post_id);

PHP - Sorting an array of data rows by price, date ASC, DESC, etc

I have an array of data which contains associative array rows and I would like to sort them by price,date etc. This cannot be done via SQL as these values are not in a database - I simply have a large array with the following example data:
$data[0] = array(
'id' => '2',
'price' => '400.00',
'date' => '2012-05-21',
),
$data[1] = array(
'id' => '4',
'price' => '660.00',
'date' => '2012-02-21',
),
$data[2] = array(
'id' => '8',
'price' => '690.00',
'date' => '2012-01-21',
)
etc..................
How can I sort this variable based on a select box such as sort by price ASC/DESC and date ASC/DESC
Sorry if this is simple - I am just so used to doing it via SQL that my mind has gone blank in this case.
I think you may modify this function:
http://php.net/manual/en/function.sort.php#104464
You should use usort and define a function which sorts based on the key you want.
Check out http://www.php.net/manual/en/function.usort.php examples 2 and 4.
Below sample code will sort it by id.
$capitals = array(
array(
'id' => '2',
'price' => '400.00',
'date' => '2012-05-21',
),
array(
'id' => '1',
'price' => '660.00',
'date' => '2012-02-21',
),
array(
'id' => '0',
'price' => '690.00',
'date' => '2012-01-21',
)
);
function cmp($a, $b)
{
return strcmp($a["id"], $b["id"]);
}
usort($capitals, "cmp");
print_r($capitals);
Use usort:
function sortBySubKey(&$array, $key)
{
return usort($array, create_function('$a,$b', 'if ($a["'.$key.'"] == $b["'.$key.'"]) return 0; return ($a["'.$key.'"] < $b["'.$key.'"]) ? -1 : 1;'));
}
You should make sure that your array holds valid values in the sense of this arithmetical comparision (<), eg. you should probably pass date as a unix timestamp for this, price as a float and so on...

Insert Date into database table using Zend framework insert method

I have the foll code as:
$table_project_win = new Application_Model_DbTable_AfterWinProject();
$data_win = array(
'project_id' => $project_id,
'project_name' => $project,
'project_type_id' => $pro_type,
'start_date' => $dateStart,
'end_date' => $dateEnd,
'project_size' => $size,
'project_description' => $pro_des
);
$table_project_win->insert($data_win);
Here I get the $dateStart and $dateEnd variabled using as:
$dateStartt = $this->_getParam('dateStart');
echo 'date Start: '.$dateStartt;
$dateStart='"'.$dateStartt.'"';
$dateEndd = $this->_getParam('dateEnd');
$dateEnd='"'.$dateEndd.'"'
By using getParam I get the value of the date that the user has given input But when i will insert it into the database I use as
$dateStart='"'.$dateStartt.'"';
$dateEnd='"'.$dateEndd.'"'
But in the database table the value for date inserted is '0000-00-00' While when I echo the $dateStart which I have got through getParam It gives the correct value as '2012-12-11'.What is the reason of it??What Should I do??
replace $dateStart='"'.$dateStartt.'"';
with
$dateStart= $dateStartt ;
or
$dateStart='`'.$dateStartt.'`';

Categories