"Call to a member function format() on bool" - laravel

I need to convert a decimal number to a time. In pure php it works perfect, but when you put it in the Laravel controller, I get this error:
"Call to a member function format() on bool".
foreach($workdays as $hour){
$num1 = $hour->hours_work.'m';
$num_change1 = str_replace(',', 'h', $num1);
$hour->hours_work = DateTime::createFromFormat('H\h i\m', $num_change1)->format('H:i');
$num2 = $hour->hours_pause . 'm';
$num_change2 = str_replace(',', 'h', $num2);
$hour->hours_pause = DateTime::createFromFormat('H\h i\m', $num_change2)->format('H:i');
}
The entry would be 9.90
The departure should be 10:30
(This post has been translated via Google Translate)

If DateTime::createFromFormat produces an error, the return value will be false (boolean)

Related

PHP preg_match unknown modifier error

Message: preg_match(): Unknown modifier 'p'
Filename: core/Router.php
Line Number: 399
Backtrace:
File: /home/spdcin/public_html/demo/no-waste/index.php
Line: 292
Function: require_once
iam getting this error on line 2
$key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);
// Does the RegEx match?
//line no 2
if (preg_match('#^'.$key.'$#', $uri, $matches))
{
// Are we using callbacks to process back-references?
if ( ! is_string($val) && is_callable($val))
{
// Remove the original string from the matches array.
array_shift($matches);
// Execute the callback using the values in matches as its parameters.
$val = call_user_func_array($val, $matches);
}
// Are we using the default routing method for back-references?
elseif (strpos($val, '$') !== FALSE && strpos($key, '(') !== FALSE)
{
$val = preg_replace('#^'.$key.'$#', $val, $uri);
}
$this->_set_request(explode('/', $val));
return;
}
}
There is a problem with your regex and PHP thinks you try to apply a 'p' modifier, which is not valid.
You will probably get to know what is wrong with your regex if you do :
echo '#^'.$key.'$#';
The fact that you try to program a router indicates that $key most probably contains '#p' (common in URLs).
Solution : In your case you can escape the character '#' with backslashes. Quoted from the php documentation :
"If the delimiter needs to be matched inside the pattern it must be escaped using a backslash."
If I understand your problem correctly, surround $key with preg_quote() like this:
if (preg_match('#^'.preg_quote($key).'$#', $uri, $matches))
This function will automatically escape ALL regex commands in $key.

Codeigniter CSV upload then explode

I have some code that uploads the CSV file to the specified folder, but it doesn't update the database.
public function do_upload()
{
$csv_path = realpath(APPPATH . '/../assets/uploads/CSV/');
$config['upload_path'] = $csv_path;
$config['allowed_types'] = '*'; // All types of files allowed
$config['overwrite'] = true; // Overwrites the existing file
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->layout->buffer('content', 'program/upload', $error);
$this->layout->render();
}
else
{
$image_data = $this->upload->data();
$fname = $image_data['file_name'];
$fpath = $image_data['file_path'].$fname;
$fh = fopen($fpath, "r");
$insert_str = 'INSERT INTO wc_program (JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish) VALUES '."\n";
if ($fh) {
// Create each set of values.
while (($csv_row = fgetcsv($fh, 2000, ',')) !== false) {
foreach ($csv_row as &$row) {
$row = strtr($row, array("'" => "\'", '"' => '\"'));
}
$insert_str .= '("'
// Implode the array and fix pesky apostrophes.
.implode('","', $csv_row)
.'"),'."\n";
}
// Remove the trailing comma.
$insert_str = rtrim($insert_str, ",\n");
// Insert all of the values at once.
$this->db->set($insert_str);
echo '<script type="text/javascript">
alert("Document successfully uploaded and saved to the database.");
location = "program/index";
</script>';
}
else {
echo '<script type="text/javascript">
alert("Sorry! Something went wrong please proceed to try again.");
location = "program/upload";
</script>';
}
}
}
When I run var_dump($fh); it shows: resource(89) of type (stream)
When I run var_dump($fpath) it shows: string(66) "/Applications/MAMP/htdocs/site/assets/uploads/CSV/wc_program.csv"
So it all uploads but what is wrong with it not updating the database?
I have tried all kinds of changing the fopen method but still no joy, I really need it to add to the database and the insert query and set query should do the trick but it doesn't.
Any help greatly appreciated!
You are not running any query on the database. You are mixing active record syntax with simple query syntax. The active record insert query will be executed by calling.
$this->db->insert('my_table');
db::set() does not actually query the database. It takes in a key/value pair that will be inserted or updated after db::insert() or db::update() is called. If you build the query yourself you need to use the db::query() function.
Review the active directory documentation.
You can use $this->db->query('put your query here'), but you lose the benefit of CodeIgniter's built in security. Review CodeIgniter's query functions.
I'll give you examples of just a few of the many ways you can insert into a database using CodeIgniter. The examples will generate the query from your comment. You will need to adjust your code accordingly.
EXAMPLE 1:
$result = $this->db
->set('JobRef', 911847)
->set('Area', 'Coastal')
->set('Parish', 'Yapton')
->set('AbbrWorkType', 'Micro')
->set('WorkType', 'Micro-Asphalt Surfacing')
->set('Timing', 'TBC')
->set('TrafficManagement', 'No Positive Traffic Management')
->set('Location', 'Canal Road (added PMI 16/07/12)')
->set('Duration', '2 days')
->set('Start', '0000-00-00')
->set('Finish', '0000-00-00')
->insert('wc_program');
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n\n";
print_r($result);
EXAMPLE 2 (Using an associative array):
$row = array(
'JobRef' => 911847,
'Area' => 'Coastal',
'Parish' => 'Yapton',
'AbbrWorkType' => 'Micro',
'WorkType' => 'Micro-Asphalt Surfacing',
'Timing' => 'TBC',
'TrafficManagement' => 'No Positive Traffic Management',
'Location' => 'Canal Road (added PMI 16/07/12)',
'Duration' => '2 days',
'Start' => '0000-00-00',
'Finish' => '0000-00-00'
);
$this->db->insert('wc_program', $row);
// This will do the same thing
// $this->db->set($row);
// $this->db->insert('wc_program');
echo $this->db->last_query();
Example 1 and 2 are using the Active Record. The information is stored piece by piece and then the query is built when you make the final call. This has several advantages. It allows you to build queries dynamically without worrying about SQL syntax and order of the keywords. It also escapes your data.
EXAMPLE 3 (Simple Query):
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
("911847","Coastal","Yapton","Micro","Micro-Asphalt Surfacing","TBC","No Positive Traffic Management","Canal Road (added PMI 16/07/12)","2 days","0000-00-00","0000-00-00")';
$result = $this->db->query($query);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
This way leaves all the protection against injection up to you, can lead to more errors, and is harder to change/maintain.
If you are going to do it this way you should use the following syntax, which will protect against injection.
EXAMPLE 4:
$query = 'INSERT INTO
wc_program
(JobRef, Area, Parish, AbbrWorkType, WorkType, Timing, TrafficManagement, Location, Duration, Start, Finish)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';
$row = array(
911847,
'Coastal',
'Yapton',
'Micro',
'Micro-Asphalt Surfacing',
'TBC',
'No Positive Traffic Management',
'Canal Road (added PMI 16/07/12)',
'2 days',
'0000-00-00',
'0000-00-00'
);
$result = $this->db->query($query, $row);
echo $this->db->last_query() . "\n\n";
echo "RESULT: \n";
print_r($result);
CodeIgniter will replace each "?" in the query with the corresponding value from the array after it is escaped. You can use this to run many queries that are of the same form, but have different data just by updating the $row array and benefit from CI's built in security.

Timepicker that removes times as they're selected (ajax)

I'm building a booking form for a moving business that uses a calendar combined with a start and end time. I built the timepicker with Formidable Pro, and it allows me to check "unique" on time fields which automatically removes them on the selected date. However it doesn't automatically remove the times from within the range between start and end times (ie: if someone chooses to rent a truck from 1am-3am I need 1am,2am,and 3am to be removed from future options but right now it only removes 1am and 3am) . I need to write ajax to remove the in-between times from the options. I'm not sure where to begin. This is the current ajax_time_ options function. Any push in the right direction would be appreciated.
function ajax_time_options(){
global $frmpro_settings, $frmdb, $wpdb;
//posted vars = $time_field, $date_field, $step, $start, $end, $date, $clock
extract($_POST);
$time_key = str_replace('field_', '', $time_field);
$date_key = str_replace('field_', '', $date_field);
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', trim($date)))
$date = FrmProAppHelper::convert_date($date, $frmpro_settings->date_format, 'Y-m-d');
$date_entries = FrmEntryMeta::getEntryIds("fi.field_key='$date_key' and meta_value='$date'");
$opts = array('' => '');
$time = strtotime($start);
$end = strtotime($end);
$step = explode(':', $step);
$step = (isset($step[1])) ? ($step[0] * 3600 + $step[1] * 60) : ($step[0] * 60);
$format = ($clock) ? 'H:i' : 'h:i A';
while($time <= $end){
$opts[date($format, $time)] = date($format, $time);
$time += $step;
}
if($date_entries and !empty($date_entries)){
$used_times = $wpdb->get_col("SELECT meta_value FROM $frmdb->entry_metas it LEFT JOIN $frmdb->fields fi ON (it.field_id = fi.id) WHERE fi.field_key='$time_key' and it.item_id in (". implode(',', $date_entries).")");
if($used_times and !empty($used_times)){
$number_allowed = apply_filters('frm_allowed_time_count', 1, $time_key, $date_key);
$count = array();
foreach($used_times as $used){
if(!isset($opts[$used]))
continue;
if(!isset($count[$used]))
$count[$used] = 0;
$count[$used]++;
if((int)$count[$used] >= $number_allowed)
unset($opts[$used]);
}
unset($count);
}
}
echo json_encode($opts);
die();
}

Fatal error in CodeIgniter while calling function itselft

I want to insert dynamic data into my preorder traversal table. I am using rebuild_tree technique by referencing this tutorial : http://www.sitepoint.com/hierarchical-data-database-3/
Here I modified the code as per the need in codeigniter. But when I calling function rebuild_tree in foreach loop it showing the fatal error like :
Fatal error: Maximum function nesting level of '100' reached, aborting! in /var/www/hr/system/database/drivers/mysql/mysql_driver.php on line 199 Call Stack: 0.0389 360600 1. {main}() /var/www/hr/index.php:0 0.0401 468096 2. require_once('/var/www/hr/system/core/CodeIgniter.php') /var/www/hr/index.php:240 0.0689 3798516 3. call_user_func_array() /var/www/hr/system/core/CodeIgniter.php:359 0.0689 3798588 4. Structure->add_structure() /var/www/hr/system/core/CodeIgniter.php:0 0.0689 3798632 5.
structure_model->rebuild_tree() /var/www/hr/application/controllers/test/structure.php:42 0.0701 3928356 6. structure_model->rebuild_tree() /var/www/hr/application/models/test/structure_model.php:35 0.0703 3931572 7. structure_model->rebuild_tree() /var/www/hr/application/models/test/structure_model.php:35 0.0705 3934788 8. structure_model->rebuild_tree() /var/www/hr/application/models/test/structure_model.php:35 0.0706 3938008 9.
CI_DB_driver->query() /var/www/hr/application/models/xome/structure_model.php:29 0.0848 4216988 97. CI_DB_driver->simple_query() /var/www/hr/system/database/DB_driver.php:299 0.0848 4216988 98. CI_DB_mysql_driver->_execute() /var/www/hr/system/database/DB_driver.php:453 0.0848 4216988 99. CI_DB_mysql_driver->_prep_query() /var/www/hr/system/database/drivers/mysql/mysql_driver.php:178
And Following is my code:
function rebuild_tree($parent, $left) {
$resultArr = array();
$parent = $_GET['level'];
$left = $_GET['lft'];
$right = $_GET['rgt'];
$right = $left + 1;
$sql = 'SELECT * FROM subunit WHERE level="' . $parent . '";';
$query = $this->db->query($sql);
$data = $query->result();
foreach ($data as $datap) {
$resultArr['name'] = $datap->name;
$resultArr['level'] = $datap->level;
$right = $this->rebuild_tree($resultArr['level'], $right);
}
$sql = 'UPDATE subunit SET lft=' . $left . ', rgt=' . $right . ' WHERE name="' . $parent . '";';
$query = $this->db->query($sql);
return $right + 1;
}
Is there any solution for this. Thank you.
Be careful when calling the function itself. Often it might end up calling itself forever. You need some kind of limitation.
You can check most of Codeigniters own libraries, and check the initialize(). That's a good example on how to handle a function which calls itself. Basicly it calls itself till no array remains, thus having an end.
In your case if 2 mysql rows are each other's parents or any similiar, you've opened the door for infinite loops.
Solution
The real problem in your function is that you pass an argument which is supposed to get a new value, however you override that value through your $_GET. That means that the 2nd function calls does exactly the same as the first function call, the third the same, the fourth the same and so on. Since the function calls never changes AND calls itself, your problem occur.
Change above part to:
$parent = $this->input->get('level');
$left = ($left ?: $this->input->get('lft'));
$right = $this->input->get('rgt');

Why DIA SDK get_libraryName symbol returns NULL for IDiaSymbol?

I need to find the correct .dll/.exe from where the function enumerated. For this I am using get_libraryName which to me should return file Name(.dll/.exe) in which the function was originally defined.
But It returns every time NULL(BadPtr=0x00000)..
Is there any way out to retrieve the exact file Name from where the function was being defined and used ?
Regards
Hassan
IDiaSession mSession;
DiaSourceClass mSourceClass;
IDiaSymbol mGlobalScope;
string pdbFileName = #"c:\test.pdb";
mSourceClass = new DiaSourceClass();
mSourceClass.loadDataFromPdb(pdbFileName);
mSourceClass.openSession(out mSession);
mSession.loadAddress = loadAddress;
mGlobalScope = mSession.globalScope;
IDiaEnumSymbols methodSymbols;
mGlobalScope.findChildren(SymTagEnum.SymTagFunction, null, 0, out methodSymbols);
foreach (IDiaSymbol methodSymbol in methodSymbols)
{
string projectName = functionSymbol.lexicalParent.name;
}
Hope this helps !

Resources