Mostrando entradas con la etiqueta mysql. Mostrar todas las entradas
Mostrando entradas con la etiqueta mysql. Mostrar todas las entradas

martes, 19 de abril de 2011

PHP and MySQL timezones


<?php
define('TIMEZONE', 'America/New_York');
We'll use that to set PHP's default timezone:

date_default_timezone_set(TIMEZONE);
What about MySQL? It's possible to set its default timezone at the start of every session -- I'd recommend doing it after you've connected to the database. The command is:

SET time_zone='offset';
where offset is a string value representing the difference to UTC/GMT, e.g. '-4:00', '+3:00', '+10:30', etc. Note that the +/- sign is essential -- even for zero -- and timezone offsets are not necessarily a whole hour. So let's write a little PHP to parse the timezone offset and format a string MySQL can understand. First, we'll create a new DateTime object, find the offset in seconds, and convert it to minutes:

$now = new \DateTime();
$mins = $now->getOffset() / 60;
We can now calculate whole hours and minutes. The first line determines whether the offset is positive or negative, then converts the value to a positive number to make the calculation easier:

$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;

PHP's sprintf function can then be used to format the string:

$offset = sprintf('%+d:%02d', $hrs*$sgn, $mins);
Finally, we execute the SET time_zone command. The following lines provide an example, but you should use your own database library where possible:

$db = new \PDO('mysql:host=localhost;dbname=test',

  'dbuser',
'dbpassword');
$db->exec("SET time_zone='$offset';");
The PHP and MySQL timezones are now synchronized within your application.

viernes, 4 de marzo de 2011

Mysql mejor tipo de campo para guardar ip

Cuando necesitamos guardar direcciones IP en nuestras bases de datos, lo más cómodo (y que casi hacemos por inercia) es asignar al campo un tipo VARCHAR con una longitud de 15 caracteres. Sin embargo, existe una opción mejor que poco a poco voy encontrándome en los principales CMS y Frameworks: INT UNSIGNED.
Así, utilizando el comando de MySQL INET_ATON, la dirección IP quedaría codificada en una cadena de 4 bytes que podríamos recuperar mediante su contrario INET_NTOA. Veamoslo con ejemplos:


# Tomamos una direccion IP y la convertimos en una cadena de enteros:     SELECT INET_ATON('192.168.0.10') AS ipn;
# Esto se traduciría en 3232235530 
# El proceso inverso:
     SELECT INET_NTOA(3232235530) AS ipa;
# Nos devuelve nuestra direccion IP anterior: 192.168.0.10