$ sudo apt-get install php5-intl
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)