Conectando a psql
root@desarrollo:~# psql -U kylix -h localhost -p 5432 sigiems
\? ayuda de psql
\p no dice que es lo que hay en buffer
\g ejecuta el script que esta el buffer
\r : Para borrar el contenido del buffer utilizamos backslash-r
\h : Para ayuda con sentencias SQL utilizamos backslash-h
\q : Para salir del cliente de programación usamos backslash-q
\l : Para ver todas las bases de datos podemos utilizar psql
sigiems-# \i /home/cesar/scripts/prueba.sql
Crear base de datos
root@desarrollo:~# su postgres
postgres@desarrollo:/home/cesar$ createdb prueba
postgres@desarrollo:/home/cesar$ psql prueba
psql (9.0.5)
Digite «help» para obtener ayuda.
prueba=#
miércoles, 5 de diciembre de 2012
martes, 4 de diciembre de 2012
Antes de Postgresql instalar las dependencias
- make: Sirve para compilar archivos fuente, despues de configurarlos
- g++: Lo necesita PostgreSQL por el lenguaje en el que fue creado
- libreadline-dev: Facilitar administracion, autocompletado
- zlib1g-dev: para usar gzip con postgresql
cms@desarrollo:~$ sudo apt-get install make g++ libreadline-dev zlib1g-dev
Obtener Postgresql
La forma de descargarlo:
wget http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2
Verificacion de Firma
http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2.md5
Debe ser identica la firma y con eso verificaremos que no se a corrupto
cms@desarrollo:~$ md5sum postgresql-9.2.1.tar.bz2
c0b4799ea9850eae3ead14f0a60e9418 postgresql-9.2.1.tar.bz2
cms@desarrollo:~$ cat postgresql-9.2.1.tar.bz2.md5
c0b4799ea9850eae3ead14f0a60e9418 postgresql-9.2.1.tar.bz2
Son identicas.
wget http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2
Verificacion de Firma
http://ftp.postgresql.org/pub/source/v9.2.1/postgresql-9.2.1.tar.bz2.md5
Debe ser identica la firma y con eso verificaremos que no se a corrupto
cms@desarrollo:~$ md5sum postgresql-9.2.1.tar.bz2
c0b4799ea9850eae3ead14f0a60e9418 postgresql-9.2.1.tar.bz2
cms@desarrollo:~$ cat postgresql-9.2.1.tar.bz2.md5
c0b4799ea9850eae3ead14f0a60e9418 postgresql-9.2.1.tar.bz2
Son identicas.
lunes, 5 de noviembre de 2012
Comandos postgresql en linux
psql -U user -h 10.12.0.0 base
por
sergioalesab
@
03 jul. 2009
– 08:43:43
Comandos sobre la linea de comandos
Borrar base de datos:
$ dropdb dbname
Crear base de datos
$ createdb dbname
Ejecutar script sobre base de datos
$ psql -f dump.sql dbname
Exportar base de datos:
$pg_dump dbname [-U username] > dump.sql
Exportar solo los datos(no el esquema)base de datos:
$pg_dump -a dbname [-U username] > dump.sql
Exportar base de datos, la salida comienza con un creado de la base de datos y conexion a dicha base de datos:
$pg_dump -C dbname [-U username] > dump.sql
Exoprtar todas las bases de datos
$pg_dumpall > outfile.sql
Cliente postgresql -> comando psql
PostgreSQL command line prompt
dbname=# \l #muestra listado de las bases de datos existentes
dbname=# \d #listar tablas de base de datos actual
dbname=# \d table-name #muestra descripcion de los campo de la tabla table-name
dbname=# \c dbname # conectarse a base de datos dbname
dbname=# \h # ayuda de comandos SQL
dbname=# \? # ayuda de comandos psql
dbname=#inset, create,..... #ejecutar comandos sql
dbname=# \g o terminar las query con ;
dbname=# \q # salir
Borrar base de datos:
$ dropdb dbname
Crear base de datos
$ createdb dbname
Ejecutar script sobre base de datos
$ psql -f dump.sql dbname
Exportar base de datos:
$pg_dump dbname [-U username] > dump.sql
Exportar solo los datos(no el esquema)base de datos:
$pg_dump -a dbname [-U username] > dump.sql
Exportar base de datos, la salida comienza con un creado de la base de datos y conexion a dicha base de datos:
$pg_dump -C dbname [-U username] > dump.sql
Exoprtar todas las bases de datos
$pg_dumpall > outfile.sql
Cliente postgresql -> comando psql
PostgreSQL command line prompt
dbname=# \l #muestra listado de las bases de datos existentes
dbname=# \d #listar tablas de base de datos actual
dbname=# \d table-name #muestra descripcion de los campo de la tabla table-name
dbname=# \c dbname # conectarse a base de datos dbname
dbname=# \h # ayuda de comandos SQL
dbname=# \? # ayuda de comandos psql
dbname=#inset, create,..... #ejecutar comandos sql
dbname=# \g o terminar las query con ;
dbname=# \q # salir
domingo, 23 de septiembre de 2012
$(document).ready(function() {
$('#selected-plays > li').addClass('horizontal');
$('#selected-plays li:not(.horizontal)').addClass('sub-level');
});
La utiliza el combinador hijo (>) para añadir la clase horizontal a todos los elementos del nivel superior unicamente. En efecto, el selector dentro de la función $() dice, encontrar todo elemento de la lista (li) que es un hijo (>) del elemento con ID de selected-plays(#selected-plays)
$('#selected-plays > li').addClass('horizontal');
$('#selected-plays li:not(.horizontal)').addClass('sub-level');
});
La utiliza el combinador hijo (>) para añadir la clase horizontal a todos los elementos del nivel superior unicamente. En efecto, el selector dentro de la función $() dice, encontrar todo elemento de la lista (li) que es un hijo (>) del elemento con ID de selected-plays(#selected-plays)
jueves, 12 de julio de 2012
Instalar MySQL Workbench en ubuntu 12.04 LTS
Instalar MySQL Workbench en ubuntu 12.04 LTS
mayo - 2 - 2012
Bien pues les cuento como es que logre instalar el Workbench.
Lo primero que debemos hacer es instalar
la siguientes librerías de acuerdo a la versión que tengas de Ubuntu si
es de 32 o de 64 bit
- https://launchpad.net/ubuntu/+archive/primary/+files/libzip1_0.9.3-1_i386.deb
- https://launchpad.net/ubuntu/+source/libzip/0.9.3-1/+build/1728114/+files/libzip1_0.9.3-1_amd64.deb
- http://launchpadlibrarian.net/94563300/libmysqlclient16_5.1.58-1ubuntu5_i386.deb
- http://launchpadlibrarian.net/94808408/libmysqlclient16_5.1.58-1ubuntu5_amd64.deb
Instalarlas es muy sencillo: lo puedes
hacer dando doble clic en el archivo o bien con el siguiente comando en
la terminal posicionándote en la ruta donde tienes el archivo.
sudo dpkg -i archivo.deb
Lo siguiente por hacer es instalar los paquetes: libzip1 python-paramiko python-pysqlite2 libctemplate0 libgtkmm-2.4-1c2a libmysqlclient16
Abrimos una terminal y ejecutamos lo siguiente:
sudo apt-get install libzip1 python-paramiko python-pysqlite2 libctemplate0 libgtkmm-2.4-1c2a libmysqlclient16
Por último solo nos queda instalar Workbench. Para esto debemos descargarlo, yo use la versión de Workbench 11.04 (x86, 32-bit), una ves descargado ejecutamos lo siguiente en una terminal:
sudo dpkg -i mysql-workbench-gpl-5.2.38-1ubu1104-i386.deb
Y con esto debe funcionar Workbench…
lunes, 9 de julio de 2012
Instalar Mysql, Apache2, php5
sudo su
apt-get install mysql-server mysql-client
apt-get install apache2
apt-get install mysql-server mysql-client
apt-get install apache2
sudo apt-get install php5 php5-gd php5-mysql php5-curl php5-cli php5-cgi php5-dev
apt-get install libapache2-mod-php5
/etc/init.d/apache2 restart
miércoles, 27 de junio de 2012
viernes, 22 de junio de 2012
Instalar Apache2 y php en ubuntu
sirgt@chapinware:~$ sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sirgt@chapinware:~$ sudo nano /etc/apt/sources.list
el contenido del fichero debe quedar asi sources.list
Luego acutalizamos los repositorios, con esto tendremos nuestro sistema al dia
sirgt@chapinware:~$ sudo aptitude update
sirgt@chapinware:~$ sudo aptitude upgrade
Primero vamos con MySQL
sirgt@chapinware:~$ sudo aptitude install mysql-server-4.1
y cambiamos la contrasenia porque por defecto se instala con la pass en blanco
sirgt@chapinware:~$ sudo /usr/bin/mysqladmin -u root password pon_tu_pass
Luego vamos con Apache y PHP5
sirgt@chapinware:~$ sudo aptitude install apache2
sirgt@chapinware:~$ sudo aptitude install php5
luego instalamos los archivos necesarios para q MySQL soporte php5 y apache2
sirgt@chapinware:~$ sudo aptitude install libapache2-mod-auth-mysql
sirgt@chapinware:~$ sudo aptitude install php5-mysql
y luego reiniciamos el servicio de apache
sirgt@chapinware:~$ sudo /etc/init.d/apache2 restart
para probar q todo haya quedado bien podemos hacer esto
sirgt@chapinware:~$ sudo gedit /var/www/test.php
Copia y pega el contenido de este archivo test.php y salvalo.
luego ve a tu firefox y apunta hacia http://localhost/test.php
si todo se instalo correctamente debe sacarte una pagina donde te da todas las especificaciones de tu php…
y listo ya tenemos nuestro servidor web Apache2 con soporte para PHP5 y MySQL
sirgt@chapinware:~$ sudo nano /etc/apt/sources.list
el contenido del fichero debe quedar asi sources.list
Luego acutalizamos los repositorios, con esto tendremos nuestro sistema al dia
sirgt@chapinware:~$ sudo aptitude update
sirgt@chapinware:~$ sudo aptitude upgrade
Primero vamos con MySQL
sirgt@chapinware:~$ sudo aptitude install mysql-server-4.1
y cambiamos la contrasenia porque por defecto se instala con la pass en blanco
sirgt@chapinware:~$ sudo /usr/bin/mysqladmin -u root password pon_tu_pass
Luego vamos con Apache y PHP5
sirgt@chapinware:~$ sudo aptitude install apache2
sirgt@chapinware:~$ sudo aptitude install php5
luego instalamos los archivos necesarios para q MySQL soporte php5 y apache2
sirgt@chapinware:~$ sudo aptitude install libapache2-mod-auth-mysql
sirgt@chapinware:~$ sudo aptitude install php5-mysql
y luego reiniciamos el servicio de apache
sirgt@chapinware:~$ sudo /etc/init.d/apache2 restart
para probar q todo haya quedado bien podemos hacer esto
sirgt@chapinware:~$ sudo gedit /var/www/test.php
Copia y pega el contenido de este archivo test.php y salvalo.
luego ve a tu firefox y apunta hacia http://localhost/test.php
si todo se instalo correctamente debe sacarte una pagina donde te da todas las especificaciones de tu php…
y listo ya tenemos nuestro servidor web Apache2 con soporte para PHP5 y MySQL
miércoles, 16 de mayo de 2012
martes, 8 de mayo de 2012
Instalacion de phpPgAdmin en Ubuntu
Instalacion de phpPgAdmin en Ubuntu
Esta es una herramienta similar a phpmyadminPara instalarla:
sudo apt-get install phppgadminla herramienta estara disponible en: http://localhost/phppgadmin
Creamos un enlace simbolico:
sudo ln -s /etc/phppgadmin/apache.conf /etc/apache2/conf.d/phppgadmin.confLo siguiente es opcional, no recomendable en ambientes de produccion.
Abrir el archivo:
sudo gedit /usr/share/phppgadmin/conf/config.inc.phpDonde dice:
$conf['extra_login_security'] = true;Dejar como:
$conf['extra_login_security'] = false;Luego de guardar el archivo anterior, recargamos Apache:
sudo /etc/init.d/apache2 reload
jueves, 3 de mayo de 2012
Instalar postgresql
apt-get -y install postgresql postgresql-client postgresql-contrib pgadmin3 pgadmin3-data libpq-dev
Instalacion de apache2, mysql, php5
$ apt-get install apache2
$ apt-get install mysql-server
$ apt-get install php5
$ apt-get install libapache2-mod-php5
$ apt-get install php5-gd
$ apt-get install php5-dom
$ apt-get install php5-pgsql
$ apt-get install php5-mysql
$ apt-get install mysql-server
$ apt-get install php5
$ apt-get install libapache2-mod-php5
$ apt-get install php5-gd
$ apt-get install php5-dom
$ apt-get install php5-pgsql
$ apt-get install php5-mysql
apt-get install php5-adodb
martes, 17 de abril de 2012
viernes, 13 de abril de 2012
Llenar un select con la base de datos
<select name=id_proveedor id=id_proveedor>
<option value=>Seleccione una opcion</option>";
$arrayObjDep = $DATABASE->getInvProveedores($valor);
if (is_array($arrayObjDep)) {
foreach ($arrayObjDep as $objDep) {
// $html .="<option value=$objDep->id_tipo_falla>$objDep->nombre</option>";
// $nombre =htmlentities($objDep->nombre);
$html .="<option value='" . $objDep->clave . "'>" . $objDep->razon_social . "</option>";
}
}
$html .="
</select>
<option value=>Seleccione una opcion</option>";
$arrayObjDep = $DATABASE->getInvProveedores($valor);
if (is_array($arrayObjDep)) {
foreach ($arrayObjDep as $objDep) {
// $html .="<option value=$objDep->id_tipo_falla>$objDep->nombre</option>";
// $nombre =htmlentities($objDep->nombre);
$html .="<option value='" . $objDep->clave . "'>" . $objDep->razon_social . "</option>";
}
}
$html .="
</select>
martes, 10 de abril de 2012
Recuperar Ubuntu tras actualizacion fallida
Inicias como recuperacion en linea de comando
Configuras la red en DHCP
# dpkg --configure -a
Configuras la red en DHCP
# dpkg --configure -a
Copiar directorios completos en ubuntu
cp -R
Ese es el comando y el argumento.
Sería así:
cp /este/directorio/locopio /en/esta/carpeta/ -R
Ese es el comando y el argumento.
Sería así:
cp /este/directorio/locopio /en/esta/carpeta/ -R
Montar discos externo en ubuntu
creas la carpete
#mkdir /media/respaldos
Para ver nuestras unidades
#mkdir -l
Montar el disco
Desmontar
#mkdir /media/respaldos
Para ver nuestras unidades
#mkdir -l
Montar el disco
# mount [dispositivo] [punto_de_montaje]
mount /dev/sdb1 /media/respaldo
Desmontar
# umount /media/disk-1
jueves, 22 de marzo de 2012
jueves, 15 de marzo de 2012
Buscar valor en un arreglo
<?php
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0);
$dish = array_search(6.50, $meals);
if ($dish) {
print "$dish costs \$6.50";
}
?>
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0);
$dish = array_search(6.50, $meals);
if ($dish) {
print "$dish costs \$6.50";
}
?>
Checar un elemento con particular Value
<?php
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0);
$books = array("The Eater's Guide to Chinese Characters",
'How to Cook and Eat in Chinese');
// This is true: key Dried Mulberries has value 3.00
if (in_array(3, $meals)) {
print 'There is a $3 item.';
}
// This is true
if (in_array('How to Cook and Eat in Chinese', $books)) {
print "We have How to Cook and Eat in Chinese";
}
// This is false: in_array( ) is case-sensitive
if (in_array("the eater's guide to chinese characters", $books)) {
print "We have the Eater's Guide to Chinese Characters.";
}
?>
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0);
$books = array("The Eater's Guide to Chinese Characters",
'How to Cook and Eat in Chinese');
// This is true: key Dried Mulberries has value 3.00
if (in_array(3, $meals)) {
print 'There is a $3 item.';
}
// This is true
if (in_array('How to Cook and Eat in Chinese', $books)) {
print "We have How to Cook and Eat in Chinese";
}
// This is false: in_array( ) is case-sensitive
if (in_array("the eater's guide to chinese characters", $books)) {
print "We have the Eater's Guide to Chinese Characters.";
}
?>
Checar un elemento con particular Key
<?php
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0); // Shrimp Puffs are free!
$books = array("The Eater's Guide to Chinese Characters",
'How to Cook and Eat in Chinese');
// This is true
if (array_key_exists('Shrimp Puffs',$meals)) {
print "Yes, we have Shrimp Puffs";
}
// This is false
if (array_key_exists('Steak Sandwich',$meals)) {
print "We have a Steak Sandwich";
}
// This is true
if (array_key_exists(1, $books)) {
print "Element 1 is How to Cook in Eat in Chinese";
}
?>
$meals = array('Walnut Bun' => 1,
'Cashew Nuts and White Mushrooms' => 4.95,
'Dried Mulberries' => 3.00,
'Eggplant with Chili Sauce' => 6.50,
'Shrimp Puffs' => 0); // Shrimp Puffs are free!
$books = array("The Eater's Guide to Chinese Characters",
'How to Cook and Eat in Chinese');
// This is true
if (array_key_exists('Shrimp Puffs',$meals)) {
print "Yes, we have Shrimp Puffs";
}
// This is false
if (array_key_exists('Steak Sandwich',$meals)) {
print "We have a Steak Sandwich";
}
// This is true
if (array_key_exists(1, $books)) {
print "Element 1 is How to Cook in Eat in Chinese";
}
?>
Alternando colores en tablas
<?php
$row_color = array('red','green');
$color_index = 0;
$meal = array('breakfast' => 'Walnut Bun',
'lunch' => 'Cashew Nuts and White Mushrooms',
'snack' => 'Dried Mulberries',
'dinner' => 'Eggplant with Chili Sauce');
print "<table>\n";
foreach ($meal as $key => $value) {
print '<tr bgcolor="' . $row_color[$color_index] . '">';
print "<td>$key</td><td>$value</td></tr>\n";
// This switches $color_index between 0 and 1
$color_index = 1 - $color_index;
}
print '</table>';
?>
$row_color = array('red','green');
$color_index = 0;
$meal = array('breakfast' => 'Walnut Bun',
'lunch' => 'Cashew Nuts and White Mushrooms',
'snack' => 'Dried Mulberries',
'dinner' => 'Eggplant with Chili Sauce');
print "<table>\n";
foreach ($meal as $key => $value) {
print '<tr bgcolor="' . $row_color[$color_index] . '">';
print "<td>$key</td><td>$value</td></tr>\n";
// This switches $color_index between 0 and 1
$color_index = 1 - $color_index;
}
print '</table>';
?>
Recorrido de arreglo con each()
Cada vez que no este seguro de los contenidos y coherencia de los arrays esta obligado a utilizar each();
Es también una muy buena herramienta para estar seguro de que no esta accediendo a arrays fuera de sus limites
<?php
$my_array = array (0 =>"elemento1", 3=>"elemento2", 4=>"elemento3", 10=>"elemento4");
while(list($key, $value)=each ($my_array))
print("Key : $key , Value: $value<br>");
?>
Resultado:
Key : 0 , Value: elemento1
Key : 3 , Value: elemento2
Key : 4 , Value: elemento3
Key : 10 , Value: elemento4
Es también una muy buena herramienta para estar seguro de que no esta accediendo a arrays fuera de sus limites
<?php
$my_array = array (0 =>"elemento1", 3=>"elemento2", 4=>"elemento3", 10=>"elemento4");
while(list($key, $value)=each ($my_array))
print("Key : $key , Value: $value<br>");
?>
Resultado:
Key : 0 , Value: elemento1
Key : 3 , Value: elemento2
Key : 4 , Value: elemento3
Key : 10 , Value: elemento4
miércoles, 14 de marzo de 2012
Activar RewriteEngine - Apache en Ubuntu
El problemilla se resolvio con un simple comando
sudo a2enmod rewrite
y reinicias el servidor
etc/init.d/apache2 restart
lunes, 12 de marzo de 2012
Funcion para hacer un insert en postgresql
function insertComponente($tipo,$nombre,$id_soporte, $conexionID=NULL){
if($conexionID==NULL){
$this->conexionID=$this->conexionBBPAE();
}
$resultado = strtoupper($nombre);
// if($visible!=1){$visible=0;}
$query="INSERT INTO cat_componente (id_area,nombre,clasif)
values ($id_soporte,'$resultado',$tipo)";
//$query=utf8_decode($query);
//echo "$query CONEXION:::".$this->conexionID.":::<br>\n";
$return=$this->funcionInsertar($query, $this->conexionID);
if (!$return){
echo $error ="ERROR:: ".time().": ".mysql_error($this->conexionID).":".$query."\n";
$tmp=0;
}else{
$error ="";
$tmp=1;
}
$control=array($tmp,$error, $query);
return $control;
}
if($conexionID==NULL){
$this->conexionID=$this->conexionBBPAE();
}
$resultado = strtoupper($nombre);
// if($visible!=1){$visible=0;}
$query="INSERT INTO cat_componente (id_area,nombre,clasif)
values ($id_soporte,'$resultado',$tipo)";
//$query=utf8_decode($query);
//echo "$query CONEXION:::".$this->conexionID.":::<br>\n";
$return=$this->funcionInsertar($query, $this->conexionID);
if (!$return){
echo $error ="ERROR:: ".time().": ".mysql_error($this->conexionID).":".$query."\n";
$tmp=0;
}else{
$error ="";
$tmp=1;
}
$control=array($tmp,$error, $query);
return $control;
}
PHP: redondeo de números decimales hacia abajo (floor) y hacia arriba
La función PHP
floor permite eliminar la
parte decimal de un número redondeándolo hacia abajo. Por ejemplo,
11.22 se redondearía a 11, 11.9999 se redondearía a 11:echo floor(11.22); // 11
echo floor(11.9999); // 11
La función PHP ceil permite eliminar la
parte decimal de un número redondeándolo hacia arriba. Por ejemplo,
11.22 se redondearía a 12, 11.9999 se redondearía a 12:echo ceil(11.22); // 12
echo ceil(11.9999); // 12
PHP: convertir cadena de texto a mayúsculas o a minúsculas
Para pasar a minúsculas:
$resultado = strtolower($origen)
Para pasar a mayúsculas:$resultado = strtoupper($origen)
jueves, 8 de marzo de 2012
Configurar la red desde dhcp
Configurar la red desde dhcp
ifconfig etho 10.0.2.144 netmask
255.255.255.0
sudo ifconfig etho 10.0.2.144 netmask
255.255.255.0
sudo ifconfig eth0 10.0.2.144 netmask
255.255.255.0
ifconfig
ping 10.0.2.254
ping google.com
ping 10.12.1.206
sudo /etc/init.d/networking restart
sudo dhclient eth0
viernes, 2 de marzo de 2012
Iniciando con Mootools
Paso 1: Descargando mootols http://www.MooTools.net/downloa
Paso 2: Agregamndo Mootools a nuestra pagina web como un enlace
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en" dir="ltr">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8" />
<title>Your title</title>
<script type="text/javascript"
src="MooTools.js"></script>
<script type="text/javascript"
src="yourSiteCode.js"></script>
<script type="text/javascript">
//or write some code in-line
</script>
</head>
<body>....</body>
</html>
Paso 2: Agregamndo Mootools a nuestra pagina web como un enlace
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en" dir="ltr">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8" />
<title>Your title</title>
<script type="text/javascript"
src="MooTools.js"></script>
<script type="text/javascript"
src="yourSiteCode.js"></script>
<script type="text/javascript">
//or write some code in-line
</script>
</head>
<body>....</body>
</html>
Traer solo un campo de un query en postgresql
function traerDepto($clave, $conexionID=NULL){
if($conexionID==NULL){
$this->conexionID=$this->conexionBBPAE();
}
$query = "SELECT nombre
FROM departamentos
WHERE clave = $clave";
//echo $query;
$qs = pg_query($query) or die (pg_error($this->conexionID). "<br>".$query);
$row = pg_fetch_row($qs);
$tmp = $row[0];
return $tmp;
}
$depto = $DATABASE->traerDepto($clave);
if($conexionID==NULL){
$this->conexionID=$this->conexionBBPAE();
}
$query = "SELECT nombre
FROM departamentos
WHERE clave = $clave";
//echo $query;
$qs = pg_query($query) or die (pg_error($this->conexionID). "<br>".$query);
$row = pg_fetch_row($qs);
$tmp = $row[0];
return $tmp;
}
$depto = $DATABASE->traerDepto($clave);
Función para traer un catalogo en postgresql
function getCat_Deptos($conexionID=NULL){
if($conexionID==NULL){
$this->conexionID=$this->conexionBBPAE();
}
$query = "SELECT *
FROM departamentos order by clave";
$qs = pg_query($query) or die (pg_error($this->conexionID). "<br>".$query);
while($res=pg_fetch_object($qs)){
$tmp[]=$res;
}
return $tmp;
}
function MostrarDeptos() {
$RH = new DB_RecursosHumanos();
$menu = "<div class='round-border-topright'></div>";
//$nombre_subperiodo=$DATABASE->getNombreSubperiodo($idsubperiodo);
// $menu .= "<h1 class='first' id='tituloMenu'>Planteles:</h1><br>";
$arrayObjSubProgramas=$RH->getCat_Deptos();
if(is_array($arrayObjSubProgramas)){
$menu .= '
<br><br><table border="1" cellspacing="0" cellpadding="0" width="50" class="list3 entries">';
foreach ($arrayObjSubProgramas as $objSubPrograma){
$menu .= "<tr class=\"Grid_EvenRow\">";
$menu .="<td><center><img src=\"img/emp.png\" width=\"16\" height=\"16\" alt=\"Selecciona Plantel\" /></center></td>";
$menu .= " <td align='left' >";
$menu .= " <div class=bloque1><h3><a href='javascript:void(0)'
class='href_t'
title='".$objSubPrograma->nombre."'
onclick=\"xajax_mostrarZP( '".$objSubPrograma->clave."')
\">".$objSubPrograma->alias."</a></h3></div>";
$menu .= " </td>";
$menu .= "</tr>";
}
$menu .= "</table>";
}
return $menu;
}
if($conexionID==NULL){
$this->conexionID=$this->conexionBBPAE();
}
$query = "SELECT *
FROM departamentos order by clave";
$qs = pg_query($query) or die (pg_error($this->conexionID). "<br>".$query);
while($res=pg_fetch_object($qs)){
$tmp[]=$res;
}
return $tmp;
}
function MostrarDeptos() {
$RH = new DB_RecursosHumanos();
$menu = "<div class='round-border-topright'></div>";
//$nombre_subperiodo=$DATABASE->getNombreSubperiodo($idsubperiodo);
// $menu .= "<h1 class='first' id='tituloMenu'>Planteles:</h1><br>";
$arrayObjSubProgramas=$RH->getCat_Deptos();
if(is_array($arrayObjSubProgramas)){
$menu .= '
<br><br><table border="1" cellspacing="0" cellpadding="0" width="50" class="list3 entries">';
foreach ($arrayObjSubProgramas as $objSubPrograma){
$menu .= "<tr class=\"Grid_EvenRow\">";
$menu .="<td><center><img src=\"img/emp.png\" width=\"16\" height=\"16\" alt=\"Selecciona Plantel\" /></center></td>";
$menu .= " <td align='left' >";
$menu .= " <div class=bloque1><h3><a href='javascript:void(0)'
class='href_t'
title='".$objSubPrograma->nombre."'
onclick=\"xajax_mostrarZP( '".$objSubPrograma->clave."')
\">".$objSubPrograma->alias."</a></h3></div>";
$menu .= " </td>";
$menu .= "</tr>";
}
$menu .= "</table>";
}
return $menu;
}
Historia de Jquery
Esta breve visión de conjunto de la historia del proyecto JQUERY describe
los cambios más significativos de una versión a otra.
Fase de desarrollo público: [ohn Resig mencionó por primera vez una mejora en
la biblioteca "Behaviour" del prototipo en agosto de 2005. Este nuevo marco de
trabajo se lanzó formalmente como jQuery el 14 de enero, 2006.
• jQuery 1.0 (agosto 2006): Ésta, la primera versión estable de la biblioteca, ya disponía de soporte robusto para selectores CSS, manejadores de evento e interacción AJAX.
jQuery 1.1 (enero 2007): Esta versión simplificaba la API considerablemente.
Muchos métodos rara vez utilizados se combinaron, reduciendo el número de
métodos a aprender y documentar.
• jQuery 1.1.3 (julio 2007): Esta versión menor contenía importantes mejoras de
velocidad para el motor selector de jQuery. A partir de esta versión, el rendimiento de jQuery se compararía favorablemente con las librerías JavaScript semejantes como Prototype, Mootools, y Dojo.
• jQuery 1.2 (septiembre 2007): La sintaxis XPath para seleccionar elementos se
eliminó en esta versión, ya que pasaba a ser redundante con la sintaxis CSS. La
personalización de efectos pasó a ser mucho más flexible en esta versión, y el
desarrollo de plug-ins pasó a ser más sencillo con la incorporación de eventos de
espacio de nombre.
• jQuery UI (septiembre 2007): Esta nueva suite de plug-in se anunció para sustituir
el plug-in popular, aunque antiguo, Interface. Se incluyó una rica colección de
widgets prefabricados, así como un conjunto de herramientas para crear elementos
sofisticados como interfaces de arrastrar y soltar.
* jQuery 1.2.6 (mayo 2008): La funcionalidad del popular plug-in Dimensions de
Brandon- Aaron se incluyó en la librería principal.
jQuery}.3 (enero 2009): Una importante revisión del motor selector (Sizzle) proporcionó
un gran impulso al reñríimiento de la librería. La delegación de evento
pasó a soportarse formalmente.
Las notas para versiones jQuery más antiguas se pueden encontrar en el sitio Web del
proyecto en http://jquery.org/history
los cambios más significativos de una versión a otra.
Fase de desarrollo público: [ohn Resig mencionó por primera vez una mejora en
la biblioteca "Behaviour" del prototipo en agosto de 2005. Este nuevo marco de
trabajo se lanzó formalmente como jQuery el 14 de enero, 2006.
• jQuery 1.0 (agosto 2006): Ésta, la primera versión estable de la biblioteca, ya disponía de soporte robusto para selectores CSS, manejadores de evento e interacción AJAX.
jQuery 1.1 (enero 2007): Esta versión simplificaba la API considerablemente.
Muchos métodos rara vez utilizados se combinaron, reduciendo el número de
métodos a aprender y documentar.
• jQuery 1.1.3 (julio 2007): Esta versión menor contenía importantes mejoras de
velocidad para el motor selector de jQuery. A partir de esta versión, el rendimiento de jQuery se compararía favorablemente con las librerías JavaScript semejantes como Prototype, Mootools, y Dojo.
• jQuery 1.2 (septiembre 2007): La sintaxis XPath para seleccionar elementos se
eliminó en esta versión, ya que pasaba a ser redundante con la sintaxis CSS. La
personalización de efectos pasó a ser mucho más flexible en esta versión, y el
desarrollo de plug-ins pasó a ser más sencillo con la incorporación de eventos de
espacio de nombre.
• jQuery UI (septiembre 2007): Esta nueva suite de plug-in se anunció para sustituir
el plug-in popular, aunque antiguo, Interface. Se incluyó una rica colección de
widgets prefabricados, así como un conjunto de herramientas para crear elementos
sofisticados como interfaces de arrastrar y soltar.
* jQuery 1.2.6 (mayo 2008): La funcionalidad del popular plug-in Dimensions de
Brandon- Aaron se incluyó en la librería principal.
jQuery}.3 (enero 2009): Una importante revisión del motor selector (Sizzle) proporcionó
un gran impulso al reñríimiento de la librería. La delegación de evento
pasó a soportarse formalmente.
Las notas para versiones jQuery más antiguas se pueden encontrar en el sitio Web del
proyecto en http://jquery.org/history
Empezando con Ajax
Paso 1) Primero nuestro archivo index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX with PHP: Iniciando</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
</html>
Paso 2) creando el archivo quickstart.js que hace referencia a el objeto XMLHttpRequest
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
4) Creamos el archivo quickstart.php
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('CRISTIAN', 'BOGDAN', 'FILIP', 'MIHAI', 'YODA');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX with PHP: Iniciando</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
</html>
Paso 2) creando el archivo quickstart.js que hace referencia a el objeto XMLHttpRequest
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
4) Creamos el archivo quickstart.php
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('CRISTIAN', 'BOGDAN', 'FILIP', 'MIHAI', 'YODA');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo
links that may help you in your journey into the exciting world of AJAX
Finally, before moving on to write your first AJAX program, here are a number of links that may help you in your journey into the exciting world of AJAX:
• http://ajaxblog.com is an AJAX dedicated blog.
• http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest is a comprehensive article collection about AJAX.
• http://www.ajaxian.com is the AJAX website of Ben Galbraith and Dion Almaer, the authors of Pragmatic AJAX.
• http://www.ajaxmatters.com is an informational site about AJAX, containing loads of very useful links.
• http://ajaxpatterns.org is about reusable AJAX design patterns.
• http://www.ajaxinfo.com is a resource of AJAX articles and links.
• http://dev.fiaminga.com contains many links to various AJAX resources and tutorials.
• http://ajaxblog.com is an AJAX dedicated blog.
• http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest is a comprehensive article collection about AJAX.
• http://www.ajaxian.com is the AJAX website of Ben Galbraith and Dion Almaer, the authors of Pragmatic AJAX.
• http://www.ajaxmatters.com is an informational site about AJAX, containing loads of very useful links.
• http://ajaxpatterns.org is about reusable AJAX design patterns.
• http://www.ajaxinfo.com is a resource of AJAX articles and links.
• http://dev.fiaminga.com contains many links to various AJAX resources and tutorials.
Understanding AJAX
AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn't say much, we agree. Simply put, AJAX can be read "empowered JavaScript", because it essentially offers a technique for client-side JavaScript to make background server calls and retrieve additional data as needed, updating certain portions of the page without causing full page reloads.
Definición de seguridad Informática
La definición de la seguridad
informática es pues como lograr adquirir, almacenar, procesar y
transmitir información en un entorno de este tipo preservando lo mas
que se pueda los servicios de:
Confidencialidad (que la
información sólo la conozcan quienes tienen derecho a ello)
Integridad (que la
información no sea alterada sin autorización)
Autenticidad (que la
información provenga de fuentes autorizadas)
Disponibilidad (que los
usuarios legítimos puedan usar la información cuando lo requieran).
En general, la seguridad
de un sistema tiene que ver con cualquier técnica, procedimiento o
medida que reduce la vulnerabilidad del sistema. La seguridad tiene
como objetivos principales lograr la confidencialidad,
integridad, autenticidad de la información y
garantizar la disponibilidad de la misma y de los
recursos de cómputo. Estos objetivos pueden translaparse o pueden
ser mutuamente exclusivos. Por ejemplo, requerimientos fuertes de
confidencialidad pueden restringir severamente la disponibilidad.
Clase pagina con constructor
<?php
// Page class
class Page {
// Declare a class member variable
var $page;
var $title;
var $year;
var $copyright;
// The constructor function
function Page($title,$year,$copyright) {
// Assign values to member variables
$this->page = '';
$this->title = $title;
$this->year = $year;
$this->copyright = $copyright;
// Call the addHeader() method
$this->addHeader();
}
// Generates the top of the page
function addHeader() {
$this->page.=<<<EOD
<html>
<head>
<title>$this->title</title>
</head>
<body>
<h1 align="center">$this->title</h1>
EOD;
}
// Adds some more text to the page
function addContent($content) {
$this->page.=$content;
}
// Generates the bottom of the page
function addFooter() {
$this->page.=<<<EOD
<div align="center">© $this->year $this->copyright</div>
</body>
</html>
EOD;
}
// Gets the contents of the page
function get() {
// Keep a copy of the page with no footer
$temp = $this->page;
// Call the addFooter() method
$this->addFooter();
// Restore $page for the next call to get
$page = $this->page;
$this->page = $temp;
return $page;
}
}
// Instantiate the page class
$webPage=new Page('As Easy as it Gets',date('Y'),'Easy Systems Inc.');
// Add something to the body of the page
$webPage->addContent(
"<p align=\"center\">It's so easy to use!</p>\n" );
// Display the page
echo ( $webPage->get() );
?>
// Page class
class Page {
// Declare a class member variable
var $page;
var $title;
var $year;
var $copyright;
// The constructor function
function Page($title,$year,$copyright) {
// Assign values to member variables
$this->page = '';
$this->title = $title;
$this->year = $year;
$this->copyright = $copyright;
// Call the addHeader() method
$this->addHeader();
}
// Generates the top of the page
function addHeader() {
$this->page.=<<<EOD
<html>
<head>
<title>$this->title</title>
</head>
<body>
<h1 align="center">$this->title</h1>
EOD;
}
// Adds some more text to the page
function addContent($content) {
$this->page.=$content;
}
// Generates the bottom of the page
function addFooter() {
$this->page.=<<<EOD
<div align="center">© $this->year $this->copyright</div>
</body>
</html>
EOD;
}
// Gets the contents of the page
function get() {
// Keep a copy of the page with no footer
$temp = $this->page;
// Call the addFooter() method
$this->addFooter();
// Restore $page for the next call to get
$page = $this->page;
$this->page = $temp;
return $page;
}
}
// Instantiate the page class
$webPage=new Page('As Easy as it Gets',date('Y'),'Easy Systems Inc.');
// Add something to the body of the page
$webPage->addContent(
"<p align=\"center\">It's so easy to use!</p>\n" );
// Display the page
echo ( $webPage->get() );
?>
Clase Page que recibe parametros
<?php
// Page class
class Page {
// Declare a class member variable
var $page;
// The constructor function
function Page() {
$this->page = '';
}
// Generates the top of the page
function addHeader($title) {
$this->page.=<<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
}
// Adds some more text to the page
function addContent($content) {
$this->page.=$content;
}
// Generates the bottom of the page
function addFooter($year,$copyright) {
$this->page.=<<<EOD
<div align="center">© $year $copyright</div>
</body>
</html>
EOD;
}
// Gets the contents of the page
function get() {
return $this->page;
}
}
// Instantiate the page class
$webPage=new Page();
// Add the header to the page
$webPage->addHeader('A Page Built with an Object');
// Add something to the body of the page
$webPage->addContent(
"<p align=\"center\">This page was generated using an object</p>\n" );
// Add the footer to the page
$webPage->addFooter(date('Y'),'Object Designs Inc.');
// Display the page
echo ( $webPage->get() );
?>
// Page class
class Page {
// Declare a class member variable
var $page;
// The constructor function
function Page() {
$this->page = '';
}
// Generates the top of the page
function addHeader($title) {
$this->page.=<<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
}
// Adds some more text to the page
function addContent($content) {
$this->page.=$content;
}
// Generates the bottom of the page
function addFooter($year,$copyright) {
$this->page.=<<<EOD
<div align="center">© $year $copyright</div>
</body>
</html>
EOD;
}
// Gets the contents of the page
function get() {
return $this->page;
}
}
// Instantiate the page class
$webPage=new Page();
// Add the header to the page
$webPage->addHeader('A Page Built with an Object');
// Add something to the body of the page
$webPage->addContent(
"<p align=\"center\">This page was generated using an object</p>\n" );
// Add the footer to the page
$webPage->addFooter(date('Y'),'Object Designs Inc.');
// Display the page
echo ( $webPage->get() );
?>
Ejemplo de una clase en php
<?php
// Page class
class Page {
// Generates the top of the page
function addHeader($page,$title) {
$page.=<<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
return $page;
}
// Generates the bottom of the page
function addFooter($page,$year,$copyright) {
$page.=<<<EOD
<div align="center">© $year $copyright</div>
</body>
</html>
EOD;
return $page;
}
}
// Inicializar variable
$page='';
// Agregar encabezado de la pagina
$page = Page::addHeader($page,'A Script Using Static Methods');
// agregar cuerpo d ela pagina
$page.=<<<EOD
<p align="center">Esta pagia es generada por metodos de una clase</p>
EOD;
// Agregar pie de pagina
$page = Page::addFooter($page,date('Y'),'Static Designs Inc.');
// Display the page
echo ( $page );
?>
// Page class
class Page {
// Generates the top of the page
function addHeader($page,$title) {
$page.=<<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
return $page;
}
// Generates the bottom of the page
function addFooter($page,$year,$copyright) {
$page.=<<<EOD
<div align="center">© $year $copyright</div>
</body>
</html>
EOD;
return $page;
}
}
// Inicializar variable
$page='';
// Agregar encabezado de la pagina
$page = Page::addHeader($page,'A Script Using Static Methods');
// agregar cuerpo d ela pagina
$page.=<<<EOD
<p align="center">Esta pagia es generada por metodos de una clase</p>
EOD;
// Agregar pie de pagina
$page = Page::addFooter($page,date('Y'),'Static Designs Inc.');
// Display the page
echo ( $page );
?>
Imprimir arreglo recursivamente
<?php
function imprimirarreglo($a) {
echo '<blockquote>';
foreach ($a as $key => $value) {
echo htmlspecialchars("$key: ");
if (is_array($value)) {
imprimirarreglo($value);
} else {
echo htmlspecialchars($value) . '<br />';
}
}
echo '</blockquote>';
}
$arr = array(
'Roman' =>
array('one' => 'I', 'two' => 'II', 'three' =>
'III', 'four' => 'IV'),
'Arabic' =>
array('one' => '1', 'two' => '2', 'three' =>
'3', 'four' => '4')
);
imprimirarreglo($arr);
?>
Resultado:
Roman:
two: 2
three: 3
four: 4
function imprimirarreglo($a) {
echo '<blockquote>';
foreach ($a as $key => $value) {
echo htmlspecialchars("$key: ");
if (is_array($value)) {
imprimirarreglo($value);
} else {
echo htmlspecialchars($value) . '<br />';
}
}
echo '</blockquote>';
}
$arr = array(
'Roman' =>
array('one' => 'I', 'two' => 'II', 'three' =>
'III', 'four' => 'IV'),
'Arabic' =>
array('one' => '1', 'two' => '2', 'three' =>
'3', 'four' => '4')
);
imprimirarreglo($arr);
?>
Resultado:
Roman:
one: IArabic: one: 1
two: II
three: III
four: IV
two: 2
three: 3
four: 4
Insert a partir de otra tabla en postgresql
INSERT INTO cat_plazas_historico (
plaza,
id_nivel,
id_depto,
z_pago,
estado,
situacion,
fecha_reg,
user_id,
fecha_mod,
user_mod,
sub_depto,
tipo_nomina,
descripcion,
tipo_plaza,
periodo )
SELECT
plaza,
id_nivel,
id_depto,
z_pago,
estado,
situacion,
fecha_reg,
user_id,
fecha_mod,
user_mod,
sub_depto,
tipo_nomina,
descripcion,
tipo_plaza,
'0' FROM cat_plazas
plaza,
id_nivel,
id_depto,
z_pago,
estado,
situacion,
fecha_reg,
user_id,
fecha_mod,
user_mod,
sub_depto,
tipo_nomina,
descripcion,
tipo_plaza,
periodo )
SELECT
plaza,
id_nivel,
id_depto,
z_pago,
estado,
situacion,
fecha_reg,
user_id,
fecha_mod,
user_mod,
sub_depto,
tipo_nomina,
descripcion,
tipo_plaza,
'0' FROM cat_plazas
Update a partir de otra tabla
UPDATE datos_emp SET tipo_pago=qna02_12.tipo_de_pago,
no_cuenta=qna02_12.no_cuenta,
no_tarjeta=qna02_12.no_targeta
FROM qna02_12 WHERE datos_emp.id_emp=qna02_12.clave_empleado
no_cuenta=qna02_12.no_cuenta,
no_tarjeta=qna02_12.no_targeta
FROM qna02_12 WHERE datos_emp.id_emp=qna02_12.clave_empleado
Como encontrar registros duplicados en postgresql
SELECT
cat_plazas.plaza
FROM
public.base_nomina,
public.cat_plazas
WHERE
cat_plazas.plaza = base_nomina.id_plaza AND
(cat_plazas.id_nivel = 14)
GROUP BY cat_plazas.plazandice
HAVING count(*) > 1 ;
cat_plazas.plaza
FROM
public.base_nomina,
public.cat_plazas
WHERE
cat_plazas.plaza = base_nomina.id_plaza AND
(cat_plazas.id_nivel = 14)
GROUP BY cat_plazas.plazandice
HAVING count(*) > 1 ;
Suscribirse a:
Entradas (Atom)