Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

15 July 2017

I've been using the wrong date delimiters in PHP for JavaScript

So I've been making dates in PHP like this

$dt = new DateTime("2017-07-15");
$date = $dt->format("Y-m-d");

and passing that to JS like this

echo "foo = new Date(\"$date\");";
// returns: Sat Jul 15 2017 00:00:00 GMT+0300 (FLE Summer Time)

and that was working fine in Chrome and Firefox. However, if you try and call foo in Safari, you'll get an invalid date error. This is because Safari doesn't currently support the dash delimiter format. More info.

To avoid this in the future, I need to start remembering to format my dates in php with / instead of - when I'm going to be using it in the web-page. So like this

$dt = new DateTime("2017/07/15");
$date = $dt->format("Y/m/d");

The only thing I can see still needing dashes, would be in URLs. If you need to switch to dashes while in JS, you can do something like .replace(/\//g, "-")

I've been neglecting testing in Safari which is pretty bad. Luckily, you can still download an old version of Safari for Windows, so testing is easy enough.

25 April 2017

Running Vagrant on Windows

Recently Packt Publishing kindly gave away Learning PHP 7 in a short 24 hour promotion. I've been going through it and had a problem setting up Vagrant 1.9.3 on Windows. Specifically running vagrant up returned this error

C:/Program Files (x86)/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.3/lib/vagrant/util/is_port_open.rb:21:in `initialize': The requested address is not valid in its context. - connect(2) for "0.0.0.0" port 8080 (Errno::EADDRNOTAVAIL) 

Here is the reported error and fix Vagrant 1.9.3 up fails.

None of this is the book's falt of course. Technology changes fast and it's tough to keep up to date with it.

Next problem I had was the book assumes you have an ssh client installed on windows, which I didn't, so the command vagrant ssh returned another error. Although this time, the error simply instructed me to install an ssh client and even suggested some. I chose Git, but found there was one more step to do after installing it. You need to add C:\Program Files\Git\bin and C:\Program Files\Git\usr\bin to your Windows environment path. This latter path contains ssh.exe along with a bunch of other tools.

Now you can easily run vagrant up and vagrant ssh from your project folder path.

The chapter index in this book looks fantastic! There are lots of new things I need to learn there, and some other things I should master. Good luck.

16 February 2017

Getting started with pagination in CodeIgniter

Intro

Sometimes your database can return a lot of data. Like hundreds (or even thousands) of rows that may need to be outputted to the user. In these kinds of situations, it’s good to use pagination, which codeigniter has an built-in library for.

Pagination is the process of dividing this data into chunks, like pages in a book. On your webpage, this often looks like a series of clickable number links, but can also be formatted to just previous and next links. Behind the scenes though, pagination works with SQL’s LIMIT and OFFSET clauses. These two clauses in essence specify a range of results (database rows) to output.

In CodeIgniter, the pagination library takes care of figuring out how many pagination links are required, and inserts the OFFSET clause value as a method argument to the controller method you are calling it from. Here is an example of just one pagination link

<a href="/language/read/20" data-ci-pagination-page="2">2</a>

How to do it

Here is how I attempted to use pagination.

Controller

public function read($pagination_offset = 0)
{
  $this->load->library('pagination');
  $pagination_config['base_url'] = base_url('language/read'); // the controller you are calling
  $pagination_config['per_page'] = 20; // sql query LIMIT number

  $this->data['languages'] = $this->language_model->get_languages($pagination_config['per_page'], $pagination_offset); // your database call with LIMIT and OFFSET arguments
  $total_query_rows = $this->db->query('SELECT id FROM languages')->num_rows(); // what the database would have yielded without the LIMIT and OFFSET clauses (*see Notes)

  $pagination_config['total_rows'] = $total_query_rows;
  $this->pagination->initialize($pagination_config); // prepares the pagination based on your configurations

  $this->data['pagination'] = $this->pagination->create_links(); // outputs the pagination as a string (*see Notes)
  $this->load->view('language', $data);
}

Model

public function get_languages($limit, $pagination_offset)
{
  $query = $this->db->query("
  SELECT
    languages.id AS id,
    languages.title AS language,
    country_code,
    COUNT(courses.id) AS number_of_courses
  FROM languages
  LEFT JOIN courses
  ON languages.id = courses.language_id
  GROUP BY languages.title
  LIMIT $limit OFFSET $pagination_offset
  ");
  return $query->result();
}

Notes

The three most important things here are

  • $pagination_config['base_url'] the controller method to call.
  • $pagination_config['per_page'] the SQL LIMIT or how many results per page you want to see.
  • $pagination_config['total_query_rows'] all the rows in the results set, so the pagination library can figure out how many links to create.

In $total_query_rows instead of writing the whole query without LIMIT and OFFSET, I wrote a much simpler one because I knew it would return the same number of rows every time.

If there is no pagination to show, create_links() will output an empty string.

In the model, you can of course use the query class library to pass LIMIT and OFFSET clauses.

Changing the view output

Above is the minimum you need to get pagination working, but it’s likely you will want to style or customise your output. To do this you can edit the default preferences which are passed to the initialize() function. I prefer to do this by creating a pagination.php file in the config folder. Here is an example using the W3.CSS front-end CSS framework

pagination.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['full_tag_open'] = '<ul class="w3-pagination w3-border w3-light-grey">';
$config['full_tag_close'] = '</ul>';

$config['first_link'] = 'First'; // might require more than 5 pages by default to show up
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
// $config['first_url'] = ''; // An alternative URL to use for the “first page” link.

$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';

$config['next_link'] = '&raquo;';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';

$config['prev_link'] = '&laquo;';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';

$config['cur_tag_open'] = '<li><b><a class="w3-green">';
$config['cur_tag_close'] = '</a></b></li>';

$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';

View

<?php if (!empty($pagination)): ?>
  <div class="w3-container">
    <div class="w3-card-2 w3-padding w3-light-grey">
      <?php echo $pagination; ?>
    </div>
  </div>
<?php endif; ?>

5 September 2016

Step-through Debugging with xdebug for php

Here is how to set up step-through debugging for php on various editors that support it. The install was on Ubnuntu 14.04.

Install by running

sudo apt-get install php5-xdebug

Next, open /etc/php5/apache2/php.ini and add the following (check the specific xdebug folder name)…

This part was giving me a message that "Module 'xdebug' already loaded". Not including the following line seems to have dismissed that message.

zend_extension="/usr/lib/php5/20121212/xdebug.so"

In the same file, find the commented line

; report_zend_debug = 0 

and uncomment it. This line apparently activates the debugging of data, but only with an installed debugger like xdebug.

Finally in php.ini, add the following settings.
Note 1: with these settings, the debugger will connect to your editor for every script it executes.
Note 2: xdebug.remote_connect_back=1 is not safe for production servers according to https://atom.io/packages/php-debug

xdebug.remote_enable=1
xdebug.remote_host=127.0.0.1
xdebug.remote_connect_back=1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=true

Save up and restart apache for changes to take effect.

sudo service apache2 restart

I had this working in both Atom and Visual Studio Code editors by installing the extension php-debug.

10 April 2016

Display in-page PHP error reporting

In-browser/in-page errors are by default turned off in php runing on apache. Obviously, you’ll only want to do this during the development phase and not when you go to production.

Here’s how to turn on PHP’s in-page error reporting on Ubuntu when developing locally.

Method 1

Open

sudo nano /etc/php5/apache2/php.ini

Locate

display_errors = Off

Replace the parameter ‘Off’ with ‘On’.

display_errors = On

Restart Apache

sudo /etc/init.d/apache2 restart

Method 2

Create a .htaccess file in your app’s root directory.

Add these three lines

php_value error_reporting -1 
php_value display_errors stdout 
php_flag display_startup_errors on