lunes, 17 de marzo de 2014

SEXTO CICLO

FRANCISCO MUNOZ
CATEDRATICO Ing. Juan Espinoza.

PROGRAMACION.NET
DEBER
TIPOS DE DATOS EN C#

Tipo C#Nombre पारा la plataforma .NETCon signo?Bytes utilizadosValores que soporta
boolSystem.BooleanNo1true o false (verdadero o falso en inglés)
byteSystem.ByteNo10 hasta 255
sbyteSystem.SByteSi1-128 hasta 127
shortSystem.Int16Si2-32.768 hasta 32.767
ushortSystem.Uint16No20 hasta 65535
intSystem.Int32Si4-2.147.483.648 hasta 2.147.483.647
uintSystem.Uint32No40 hasta 4.394.967.395
longSystem.Int64Si8-9.223.372.036.854.775.808 hasta 9.223.372.036.854.775.807
ulongSystem.Uint64No80 hasta 18446744073709551615
floatSystem.SingleSi4Approximadamente ±1.5E-45 hasta ±3.4E38 con 7 cifras significativas
doubleSystem.DoubleSi8Approximadamente ±5.0E-324 hasta ±1.7E308 con 7 cifras significativas
decimalSystem.DecimalSi12Approximadamente ±1.0E-28 hasta ±7.9E28 con 28 ó 29 cifras significativas
charSystem.Char
2Cualquier carácter Unicode (16 bits)

Conversiones de tipos en C#

Dado que a C# se le asignan tipos estáticos en tiempo de compilación, después de declarar una variable, no se puede volver a declarar ni tampoco utilizar para almacenar valores de otro tipo, a menos que dicho tipo pueda convertirse en el tipo de la variable. Por ejemplo, no existe conversión de un entero a una cadena arbitraria cualquiera. Por lo tanto, después de declarar i como entero, no puede asignarle la cadena "Hello", como se muestra en el código siguiente.
int i;
i = "Hello"; // Error: "Cannot implicitly convert type 'string' to 'int'"
 
Sin embargo, en ocasiones puede que sea necesario copiar un valor en un parámetro de método o variable de otro tipo. Por ejemplo, puede que tenga una variable de tipo entero que deba pasar a un método cuyo parámetro es de tipo double.  Estos tipos de operaciones se denominan conversiones de tipos. En C#, puede realizar los siguientes tipos de conversiones:
·         Conversiones implícitas: no se requiere una sintaxis especial porque la conversión se realiza con seguridad de tipos y no se perderán datos. Entre los ejemplos se incluyen las conversiones de tipos enteros de menor a mayor y las conversiones de clases derivadas en clases base.
·         Conversiones explícitas (conversiones de tipos): las conversiones explícitas requieren un operador de conversión. Las variables de origen y destino son compatibles, pero existe el riesgo de perder datos debido a que el tipo de la variable de destino es más pequeño que (o es una clase base de) la variable de origen.
·         Conversiones definidas por el usuario: las conversiones definidas por el usuario se realizan a través de métodos especiales que puede definir para habilitar las conversiones explícitas e implícitas entre tipos personalizados que no tienen una relación de clase base-clase derivada. Para obtener más información, vea Operadores de conversión (Guía de programación de C#).
·         Conversiones con clases auxiliares: para realizar conversiones entre tipos no compatibles, como los enteros y los objetos System..::.DateTime, o bien cadenas hexadecimales y matrices de bytes, puede utilizar la clase System..::.BitConverter, la clase System..::.Convert y los métodos Parse de los tipos numéricos integrados, como Int32..::.Parse..
   
Conversiones implícitas
En los tipos numéricos integrados, puede realizarse una conversión implícita cuando el valor que se va a almacenar puede ajustarse a la variable sin necesidad de truncamiento o redondeo. Por ejemplo, una variable de tipo longlong (Referencia de C#) (entero de 8 bytes) puede almacenar cualquier valor que pueda almacenar a su vez un elemento intint (Referencia de C#) (4 bytes en un equipo de 32 bits). En el ejemplo siguiente, el compilador convierte implícitamente el valor de la derecha en un tipo long antes de asignarlo a bigNum.
// Implicit conversion. num long can
// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;


 en C#

La instrucción if selecciona una instrucción para ejecución en base al valor de una expresión Boolean. En el ejemplo siguiente un indicador Boolean flagCheck se establece en true y, a continuación, se protege en la instrucción if. El resultado es: El indicador se pone en true. bool flagCheck = true; if (flagCheck == true) { Console.WriteLine("El flag esta true."); } else  { Console.WriteLine("El flag esta false."); }
ComentariosSi la expresión en el paréntesis se evalúa como true, a continuación se ejecuta la instrucción Console.WriteLine("El flag esta true."); . Después de ejecutar la instrucción if, el control se transfiere a la siguiente instrucción. Else no se ejecuta en este ejemplo. Si se desea ejecutar más de una instrucción, es posible ejecutar varias instrucciones en forma condicional al incluirlas en bloques mediante { }, al igual que en el ejemplo anterior. Las instrucciones que se van a ejecutar como resultado de comprobar la condición pueden ser de cualquier tipo, incluida otra instrucción if anidada dentro de la instrucción if original. En las instrucciones if anidadas, la cláusula else pertenece a la última instrucción if que no tiene una cláusula else correspondiente. Por ejemplo: if (x > 10) if (y > 20) Console.Write("Setencia_1"); else Console.Write("Sentencia_2");
En este ejemplo, se mostrará Sentencia_2 si la condición (y > 20) se evalúa como false. No obstante, si desea asociar Sentencia_2 a la condición (x >10), utilice llaves: if (x > 10) { if (y > 20) Console.Write("Sentencia_1"); } else Console.Write("Sentencia_2");
En este caso, se mostrará Sentencia_2 si la condición (x > 10) se evalúa como false. Ejemplo 1 En este ejemplo, se escribe un carácter desde el teclado y el programa comprueba si se trata de un carácter alfabético. En ese caso, comprueba si es minúscula o mayúscula. En cada caso, se muestra el mensaje apropiado. // Sentencias_if_else.cs // if-else ejemplousing System; class IfTest { static void Main() { Console.Write("Entre un caracter: "); char c = (char)Console.Read(); if (Char.IsLetter(c)) { if (Char.IsLower(c)) { Console.WriteLine("El caracter esta en minuscula."); } else { Console.WriteLine("El caracter esta en mayuscula."); } } else { Console.WriteLine("No es un caracter del alfabeto."); } } }

Resultado 2
Resultados del ejemplo Entre un caracter: 2 El caracter no es alfabético.
A continuación se ofrece otro ejemplo: Ejecución Nº 2: Entre un caracter: A El caracter está en mayúscula. Ejecución Nº 3: Entre un caracter: h El carácter esta en minúscula. También es posible extender la instrucción if de modo que puedan controlarse varias condiciones, mediante la construcción else-if siguiente: if (Condicion_1) {// Sentencia_1;} else if (Condicion_2) {// Sentencia_2;} else if (Condicion_3) {// Sentencia_3;}else{// Sentencia_n;}
Ejemplo 2Este ejemplo comprueba si el carácter especificado es una letra minúscula, mayúscula o un número. En cualquier otro caso, se tratará de un carácter no alfanumérico. El programa utiliza la anterior estructura else-if en escalera. // Sentencias_if_else2.cs // else-if using System; public class IfTest{ static void Main() { Console.Write("Entre un caracter: "); char c = (char)Console.Read(); if (Char.IsUpper(c)) { Console.WriteLine("El caracter está en mayúscula."); } else if (Char.IsLower(c)) { Console.WriteLine("El caracter está en minúscula."); } else if (Char.IsDigit(c)) { Console.WriteLine("El caracter es un numero."); } else { Console.WriteLine("El caracter no es alfanumerico."); } } }
ResultadoE
Resultados del ejemplo Entre un caracter: E El caracter esta en mayúscula
OPERADORES LOGICOS EN C#

OPERADORES ARITMÉTICOS


Binarios: los operadores binarios indican operaciones sencillas de incremento (suma o  ) y decremento (resta, división y modulo), estos son los operadores binarios:
+: representa la suma de dos o más valores o variables.
-: representa la resta de dos o más valores o variables.
*: representa la multiplicación de dos o más valores o variables.
/: representa la división de dos o más valores o variables.
%: representa el modulo (obtención del residuo de una división) de dos o más valores o variables.
Unarios: los operadores unarios representan operaciones simplificadas de incremento decremento y modificación de signos, estos son los operadores unarios:
++: Incrementa el valor de una variable en una unidad.
--: Decrementa el valor de una variable en una unidad.
-: Cambia el signo de una variable, es como multiplicar por -1.

OPERADORES RELACIONALES

  Son operadores que se encargan de unir y comparar dos o más valores, siempre se utilizan en comparaciones de parejas y están dadas por los símbolos: == : igual que != : diferente a > : mayor que < : menor que >= : mayor igual que <= : menor igual que Estos operadores se usan para comparar valores de variables por pares es decir,no se pueden comparar más de 2 valores al tiempo:
a > b > c //ERROR
(a > b) && (b > c) //BIEN

OPERADORES LÓGICOS

Son operadores de unión, también llamados compuertas lógicas, estos operadores pueden unir dos o más pares de valores comparados por medio de los operadores relaciones y están dados por estos símbolos: && : Operador AND (Y) quiere decir que todas las condiciones deben ser verdaderas para que se ejecute una acción. || : Operador OR (O) quiere decir que de todas las condiciones solo una debe ser verdadera y se asume que con eso es suficiente para hacer determinada acción. ! : Operdaro NOT (NO) quiere decir que se niega la afirmación para cambiar su valor, es decir cambia de verdadero a falso y de falso a verdadero.

SEXTO CICLO

FRANCISCO MUNOZ
CATEDRATICO: Ing Juan Espinoza.

PROGRAMACION.NET
PRACTICA
MAYOR, MENOR DE TRES NUMEROS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MAYORMENORIGUAL
{
    class Program
    {
        static void Main(string[] args)
        {
               int X,Y;  
            Console.WriteLine("Ingrese un numero");  
         int A = Convert.ToInt16(Console.ReadLine());  
            Console.WriteLine("Ingrese un numero");  
         int B = Convert.ToInt16(Console.ReadLine());  
            Console.WriteLine("Ingrese un numero");  
         int C = Convert.ToInt16(Console.ReadLine());  
          
         if (A > B && A > C)  
         {  
             X = A;  
         }  
         else  
         {  
             if (B > A && B > C )  
             {  
                 X = B;  
             }  
             else  
             {  
                 if (C > A && C > B)  
                 {  
                     X = C;  
                 }  
                 else  
                     X = C;  
             }  
         }
         if (A < B && A < C)
         {
             Y = A;
         }
         else
         {
             if (B < A && B < C)
             {
                 Y = B;
             }
             else
             {
                 if (C < A && C < B)
                 {
                     Y = C;
                 }
                 else
                 {
                     Y = C;
                 }
             }
         } 
         Console.WriteLine("el mayor es " + X + " y el menor es " + Y);  
            Console.ReadLine();  
        }  
    }  

SEXTO CICLO

FRANCISCO MUNOZ
CATEDRATICO: Ing Juan Espinoza.

PROGRAMACION.NET
PRACTICA
CARATULA

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace caratula
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\t\t\t\tNOMBRE:");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\t\t\t\tFrancisco Munoz");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\t\t\t\tCICLO:");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\t\t\t\tSexto Sistemas");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\t\t\t\tCATEDRATICO:");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\t\t\t\tIng.Juan Espinoza");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\t\t\t\tMATERIA:");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\t\t\t\tProgramacion.NET");
            Console.WriteLine("\n\t\t\t\tCICLO LECTIVO:");
            //Console.BackgroundColor = ConsoleColor.DarkRed;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\t\t\t\tFebrero 2014-Julio 2014");
            Console.ReadLine(); //pausa en pantalla
        }
    }
}

jueves, 30 de enero de 2014

DEBER 28

FRANCISCO MUNOZ
CATEDRATICO Ing. Juan Espinoza

CONEXION A BASE DE DATOS
<?php
$conexion=mysql_connect("localhost","CONEXIONBDD","admin");
if(!$conexion){
die('NO SE PUDO ESTABLECER LA CONEXION'.mysql_error());
}
else{
echo("CONEXION SATISFACTORIA");
}
mysql_select_db("BDDAGENDA", $conexion);

?>

EDITAR
<?php
if(isset($_POST["btn1"])){
$btn=$_POST["btn1"];

if($btn=="Listar"){

$sql="select * from agenda";
$cs=mysql_query($sql,$conexion);
echo"<center>
<table border='3'>
<tr>
<td>Codigo</td>
<td>Nombre</td>
<td>Apellido</td>
<td>Edad</td>
<td>Telefono</td>
<td>Direccion</td>
<td>Ciudad</td>
<td>Sexo</td>

</tr>";
while($resul=mysql_fetch_array($cs)){
$var=$resul[0];
$var1=$resul[1];
$var2=$resul[2];
$var3=$resul[3];
$var4=$resul[4];
$var5=$resul[5];
$var6=$resul[6];
$var7=$resul[7];
echo "<tr>

<td>$var</td>
<td>$var1</td>
<td>$var2</td>
<td>$var3</td>
<td>$var4</td>
<td>$var5</td>
<td>$var6</td>
<td>$var7</td>
<td><a href='actualizar.php' name='btn1'>Modificar</a></td>
</tr>";
}
ECHO "<H1><CENTER>LISTA</CENTER></H1>";
//echo '<td>'.'<a href="actualizar.php" value="Editar">'.'Modificar'.'</a>'.'</td>';
echo "</table>

</center>";

}
}
?>

ELIMINAR
<?php
if(isset($_POST["btn1"])){
$btn=$_POST["btn1"];

if($btn=="Eliminar"){

$sql="delete * from agenda";
$cs=mysql_query($sql,$conexion);
echo"<center>
<table border='3'>
<tr>
<td>Codigo</td>
<td>Nombre</td>
<td>Apellido</td>
<td>Edad</td>
<td>Telefono</td>
<td>Direccion</td>
<td>Ciudad</td>
<td>Sexo</td>

</tr>";
while($resul=mysql_fetch_array($cs)){
$var=$resul[0];
$var1=$resul[1];
$var2=$resul[2];
$var3=$resul[3];
$var4=$resul[4];
$var5=$resul[5];
$var6=$resul[6];
$var7=$resul[7];
echo "<tr>

<td>$var</td>
<td>$var1</td>
<td>$var2</td>
<td>$var3</td>
<td>$var4</td>
<td>$var5</td>
<td>$var6</td>
<td>$var7</td>
<td><a href='eliminar.php' name='btn1'>Eliminar</a></td>
</tr>";
}
ECHO "<H1><CENTER>LISTA</CENTER></H1>";
echo "</table>

</center>";

}
}
?>

martes, 21 de enero de 2014

DEBER 27

FRANCISCO MUNOZ
CATEDRATICO Ing. Juan Espinoza.

RESULTADO FINAL





PRIMERO NOS CONECTAMOS A LA BASE DE DATOS
<?php
$conexion=mysql_connect("localhost","CONEXIONBDD","admin");
if(!$conexion){
die('NO SE PUDO ESTABLECER LA CONEXION'.mysql_error());
}
else{
echo("CONEXION SATISFACTORIA");
}

AHORA SELECCIONAMOS LA BASE DE DATOS
mysql_select_db("BDDAGENDA", $conexion);
?>

DENTRO DE UN HTML REALIZAMOS LA CODIFICACION PHP
<html>
<head>
<title>DATOS</title>
</head>
<body bgcolor="celeste">
<section id="top">
<h1><CENTER>LISTAR DATOS</CENTER></h1>
</section>
<?php
$var="";
$var1="";
$var2="";
$var3="";
$var4="";
$var5="";

EXTRAEMOS LOS DATOS CON LA SENTENCIA IF Y ISSET
if(isset($_POST["btn1"])){
$btn=$_POST["btn1"];
$bus=$_POST["txtbus"];
$bus1=$_POST["txtapel"];
$bus2=$_POST["txtedad"];
$bus3=$_POST["txtdire"];

AQUI PREGUNTAMOS SI PRESIONA NOMBRE QUE REALICE LA SIGUIENTE CONSULTA



if($btn=="Nombre"){
$sql="select * from agenda where Nombre='$bus'";
$cs=mysql_query($sql,$conexion);
?>
<table width="1166" border="1" id="tab">
   <tr>
     <td width="19">Id </td>
     <td width="61">Nombre</td>
     <td width="157">Apellido</td>
     <td width="221">Edad</td>
     <td width="176">Direccion</td>
     <td width="107">Telefono</td>
   </tr>
   <?php
while($resul=mysql_fetch_array($cs)){
echo '<tr>';
echo '<td width="19">'.$resul['idagenda'].'</td>';
echo '<td width="61">'.$resul['Nombre'].'</td>';
echo '<td width="157">'.$resul['Apellido'].'</td>';
echo '<td width="221">'.$resul['Edad'].'</td>';
echo '<td width="176">'.$resul['Direccion'].'</td>';
echo '<td width="107">'.$resul['Telefono'].'</td>';
echo '</tr>';
}
}

AQUI CONSULTA PARA EL NOMBRE
if($btn=="Apellido"){

$sql="select * from agenda where Apellido='$bus1'";
$cs1=mysql_query($sql,$conexion);
?>
<table width="1166" border="1" id="tab">
   <tr>
     <td width="19">Id </td>
     <td width="61">Nombre</td>
     <td width="157">Apellido</td>
     <td width="221">Edad</td>
     <td width="176">Direccion</td>
     <td width="107">Telefono</td>
   </tr>
   <?php
while($resul=mysql_fetch_array($cs1)){
echo '<tr>';
echo '<td width="19">'.$resul['idagenda'].'</td>';
echo '<td width="61">'.$resul['Nombre'].'</td>';
echo '<td width="157">'.$resul['Apellido'].'</td>';
echo '<td width="221">'.$resul['Edad'].'</td>';
echo '<td width="176">'.$resul['Direccion'].'</td>';
echo '<td width="107">'.$resul['Telefono'].'</td>';
echo '</tr>';
}
}

AQUI CONSUTA PARA LA EDAD
if($btn=="Edad"){

$sql="select * from agenda where Edad='$bus2'";
$cs2=mysql_query($sql,$conexion);
?>
<table width="1166" border="1" id="tab">
   <tr>
     <td width="19">Id </td>
     <td width="61">Nombre</td>
     <td width="157">Apellido</td>
     <td width="221">Edad</td>
     <td width="176">Direccion</td>
     <td width="107">Telefono</td>
   </tr>
   <?php
while($resul=mysql_fetch_array($cs2)){
echo '<tr>';
echo '<td width="19">'.$resul['idagenda'].'</td>';
echo '<td width="61">'.$resul['Nombre'].'</td>';
echo '<td width="157">'.$resul['Apellido'].'</td>';
echo '<td width="221">'.$resul['Edad'].'</td>';
echo '<td width="176">'.$resul['Direccion'].'</td>';
echo '<td width="107">'.$resul['Telefono'].'</td>';
echo '</tr>';
}
}

AQUI CONSULTA PARA QUE MUESTRE DIRECCIONES IGUALES
if($btn=="Direccion"){

$sql="select * from agenda where Direccion='$bus3'";
$cs3=mysql_query($sql,$conexion);
?>
<table width="1166" border="1" id="tab">
   <tr>
     <td width="19">Id </td>
     <td width="61">Nombre</td>
     <td width="157">Apellido</td>
     <td width="221">Edad</td>
     <td width="176">Direccion</td>
     <td width="107">Telefono</td>
   </tr>
   <?php
while($resul=mysql_fetch_array($cs3)){
echo '<tr>';
echo '<td width="19">'.$resul['idagenda'].'</td>';
echo '<td width="61">'.$resul['Nombre'].'</td>';
echo '<td width="157">'.$resul['Apellido'].'</td>';
echo '<td width="221">'.$resul['Edad'].'</td>';
echo '<td width="176">'.$resul['Direccion'].'</td>';
echo '<td width="107">'.$resul['Telefono'].'</td>';
echo '</tr>';
}

}
?>

</table>
AHORA AGREGAMOS LAS CONSULTAS PARA LOS BOTONES 

NUEVO
<?php
if($btn=="Nuevo"){
$sql="select count(idagenda),Max(idagenda) from agenda";
$cs=mysql_query($sql,$conexion);
while($resul=mysql_fetch_array($cs)){
$count=$resul[0];
$max=$resul[1];
}
if($count==0){
$var="A0001";
}
else{
$var='A'.substr((substr($max,1)+10001),1);
}
}

AGREGAR
if($btn=="Agregar"){
$cod=$_POST["txtcod"];
$nom=$_POST["txtnom"];
$ape=$_POST["txtape"];
$eda=$_POST["txteda"];
$tel=$_POST["txttel"];
$dir=$_POST["cbosex"];
$sql="insert into agenda values ('$cod','$nom','$ape','$eda','$tel','$dir')";
$conexion=mysql_query($sql,$conexion);
echo "<script> alert('Se Inserto; correctamente');</script>";
}
ELIMINAR
if($btn=="Eliminar"){
$cod=$_POST["txtcod"];
$sql="delete from agenda where idagenda='$cod'";
$cs=mysql_query($sql,$conexion);
echo "<script> alert('Se elimnino correctamente');</script>";
}
}

?>
AQUI CON CODIGO HTML REALIZAMOS LOS CAMPOS PARA INGRESAR DATOS:
<form name="fe" action="" method="post">
<center>
CODIGO
<table border="2">
<tr>
<td>Codigo</td>
<td><input type="text" name="txtcod" value="<?php echo $var?>" /></td>
</tr>
NOMBRE
<tr>
<td>Nombre</td>
<td><input type="text" name="txtnom"  value="<?php echo $var1?>"/></td>
</tr>
APELLIDO
<tr>
<td>Apellido</td>
<td><input type="text" name="txtape"  value="<?php echo $var2?>"/></td>
</tr>
EDAD
<tr>
<td>Edad</td>
<td><input type="text" name="txteda"  value="<?php echo $var3?>"/></td>
</tr>
TELEFONO
<tr>
<td>Telefono;</td>
<td><input type="text" name="txttel"  value="<?php echo $var4?>"/></td>
</tr>
DIRECCION
<tr>
<td>Direccion</td>
<td><input type="text" name="cbosex"  value="<?php echo $var5?>"/></td>
</tr>

Y AQUI PONEMOS LOS BOTONES:
<tr align="center">
<td colspan="2">
NUEVO
<input type="submit" name="btn1" value="Nuevo"/>
LISTAR
<input type="submit" name="btn1" value="Listar"/>
ELIMINAR
<input type="submit" name="btn1"value="Eliminar"/>
AGREGAR
<input type="submit" name="btn1"value="Agregar"/></td></tr>
</table >

AQUI CREAMOS LOS CAMPOS Y BOTONES PARA FILTRAR CON CODIGO HTML
<table color="green" border="2">
<tr>
POR NOMBRE:
<td>Filtrar</td>
<td><input type="text" name="txtbus"/></td>
<td><input type="submit" name="btn1"  value="Nombre"  /></td>
POR APELLIDO:
<td>Filtrar</td>
<td><input type="text" name="txtapel"/></td>
<td><input type="submit" name="btn1"  value="Apellido"  /></td>
POR EDAD:
<td>Filtrar</td>
<td><input type="text" name="txtedad"/></td>
<td><input type="submit" name="btn1"  value="Edad"  /></td>
POR DIRECCION:
<td>Filtrar</td>
<td><input type="text" name="txtdire"/></td>
<td><input type="submit" name="btn1"  value="Direccion"  /></td>

</center>
<br />
<hr>
</form>
<br />


AQUI PROGRAMAMOS PARA QUE NO MUESTRE EN UNA TABLA LA LISTA CON TODOS SUS CAMPOS OSEA DESPUES DE PRESIONAR LA TECLA LISTAR.




<?php
if(isset($_POST["btn1"])){
$btn=$_POST["btn1"];

if($btn=="Listar"){
$sql="select * from agenda";
$cs=mysql_query($sql,$conexion);
echo"<center>
<table border='3'>
<tr>
<td>Codigo</td>
<td>Nombre</td>
<td>Apellido</td>
<td>Edad</td>
<td>Telefono</td>
<td>Direccion</td>
</tr>";
while($resul=mysql_fetch_array($cs)){
$var=$resul[0];
$var1=$resul[1];
$var2=$resul[2];
$var3=$resul[3];
$var4=$resul[4];
$var5=$resul[5];
echo "<tr>

<td>$var</td>
<td>$var1</td>
<td>$var2</td>
<td>$var3</td>
<td>$var4</td>
<td>$var5</td>

</tr>";
}
ECHO "<H1><CENTER>LISTA</CENTER></H1>";
echo "</table>

</center>";

}
}
?>
</body>
</html>

miércoles, 18 de diciembre de 2013

DEBER 26

FRANCISCO MUNOZ
CATEDRATICO Ing. Juan Espinoza

EJEMPLOS DE COMANDOS

INSERT
INSERT INTO clientes(nombre, direccion, ciudad, telefono, codempresa) VALUES ('Carlos Rios', 'Caseros 2417', 'Buenos Aires', '48485825', 23)

UPDATE
UPDATE clientes SET nombre= 'Carlos Rios' WHERE nombre= 'Carlos Rioso'

DELETE
DELETE FROM clientes WHERE ciudad= 'Mar del Plata'

SELECT
SELECT "nombre_columna" FROM "nombre_tabla";

lunes, 16 de diciembre de 2013

DEBER 25


FRANCISCO MUNOZ
CATEDRATICO Ing Juan Es pinoza.

QUE ES SQL?
SQL es un lenguaje creado para realizar consultas estructuradas a bases de datos. 
SQL son las siglas de Structured Query Language (Lenguaje estructurado de consultas). 
No es exclusivo para paginas web, Aplicaciones de escritorio tambien lo utilizan ya que permite que las consultas a las tablas de alguna base de datos sea mas rapida y segura. 


El lenguaje se divide en dos partes: 
-El lenguaje de definicion de datos (DDL): son los comandos que nos permiten la creacion y modificacion de los objetos de la base de datos. Son 4 los comandos: CREATE, ALTER, DROP y TRUNCATE. 
* CREATE: Nos permite crear un objeto (una tabla, un procedimiento almacenado, un indice, etc.) 
* ALTER: Con este comando podemos modificar la estructura de algun objeto: una columna de una tabla, modificar tipos de campo, anchos, keys de los indices, etc... 
* DROP: Este nos va a borrar algun objeto (una columna, un procedimiento, etc) 
* TRUNCATE: Este es cuando kieres borrar de plano los datos de alguna tabla y solo te dejara la estructura. 

- Y el lenguaje de manipulacion de datos(DML): Este ya es para trabajo de manejo de datos directo, los comandos son: INSERT, UPDATE, DELETE y SELECT. 
* INSERT: Este nos permite introducir datos a una tabla. 
* UPDATE: Sirve para actualizar datos ya existentes dentro de la tabla. 
* DELETE: Con este eliminamos datos desde una tabla. 
* SELECT: Este sirve para seleccionar datos de una tabla. 


BIBLIOGRAFIA
http://answers.yahoo.com/question/index?qid=20080919180523AAg7GGC

EVENTOS
mysql_select_db()
 Selecciona la base de datos por defecto para realizar las consultas, en la conexión activa.

mysql_query()
envía una única consulta (múltiples consultas no están soportadas) a la base de datos actualmente activa en el servidor asociado con el identificador de enlace especificado por link_identifier.

mysql_close
 cierra la conexión no persistente al servidor de MySQL que está asociada con el identificador de enlace especificado. Si link_identifier no se especifica, se usará el último enlace abierto.
Normalmente no es necesario usar a mysql_close(), ya que los enlaces abiertos no persistentes son automáticamente cerrados al final de la ejecución del script. Véase también liberar recursos.

mysql_connect
Abre o reutiliza una conexión a un servidor MySQL.

BIBLIOGRAFIA


VARIABLES
$result
El resultado resource que está siendo evaluado. Este resultado proviene de una llamada a mysql_query().
ejemplo
<?php
$enlace 
mysql_connect('anfitrión_mysql''usuario_mysql''contraseña_mysql');
if (!
$enlace) {
    die(
'No se pudo conectar: ' mysql_error());
}
if (!
mysql_select_db('nombre_base_datos')) {
    die(
'No se pudo seleccionar la base de datos: ' mysql_error());
}
$resultado mysql_query('SELECT name FROM work.employee');
if (!
$resultado) {
    die(
'No se pudo consultar:' mysql_error());
}
echo 
mysql_result($resultado2); // imprime el nombre del tercer empleado
mysql_close($enlace);?>
 $print 
Mostrar una cadena

BIBLIOGRAFIA

miércoles, 11 de diciembre de 2013

DEBER 24

FRANCISCO MUNOZ
CATEDRATICO Ing Juan Espinoza.

MENU PRINCIPAL.

<?php
echo "<html>
<head><title>Suma</title>
<style type='text/css'>
[required]{
border-color:red;
box-shadow:0px 0px 5px black;
}
</style>
</head>
<body bgcolor='IVORY' text='BLACK'>
<>
<h1> Escoja la opcion que desee </h1>
<h3>1    2   3<h3>
<table border=2>
<form action='operaciones.php' method='POST'>
<tr><td>Ingrese la opcion : </td>
<td><input name='opcion' required></td>
</tr>
<tr><td>Ingrese el correo : </td>
<td><input name='cor' required></td>
</tr>
<tr><td>Ingrese el nombre : </td>
<td><input name='nom' required></td>
</tr>
<tr><td>Ingrese la clave : </td>
<td><input type='password' name='cla' required></td>
</tr>
<tr>
<tr><td><H3><input type='submit' value='Procesar' name='pro'></H3>
</tr>
</table>
</form>
</center>
</body>
</html>
?>

SI INICIA SESION CON SUS DATOS CORRECTOS MUESTRA ESTO.

<?php
session_start();
$_SESSION['nombre']=$_REQUEST['nom'];
$_SESSION['clave']=$_REQUEST['cla'];
$_SESSION['correo']=$_REQUEST['cor'];

if ($_SESSION['nombre']=="admin" && $_SESSION['correo']=="admin@admin.com" && $_SESSION['clave']=="admin")
{
$op = $_POST['opcion'];
echo "<head><body bgcolor='ivory' text='black'><center><h1>Prueba</h1>";
class Operacion {
var $Nombre;
var $Clave;
var $Correo;
function iniciar($nombre,$clave,$correo){
echo "<br> Inicializar <br>";
$this->Nombre=$nombre;
$this->Clave=$clave;
$this->Correo=$correo;
echo "<br> a inicializado : ".$this->Nombre." con la clave ".$this->Clave." y el correo ".$this->Correo;
}
function registrar($nombre,$clave,$correo){
echo "<br> Registrar <br>";
$this->Nombre=$nombre;
$this->Clave=$clave;
$this->Correo=$correo;
echo "<br> a registrado : ".$this->Nombre." su clave es ".$this->Clave." y su correo ".$this->Correo;
}
function cerrar($nombre,$clave,$correo){
echo "<br> Cerrar <br>";
$this->Nombre=$nombre;
$this->Clave=$clave;
$this->Correo=$correo;
echo "<br> Cerro : ".$this->Nombre." con la clave ".$this->Clave." y el correo ".$this->Correo;
}
}
$operacion= new Operacion(" Opciones de Session <br>");
switch($op)
{
case 1:
$op1=$operacion->Iniciar($_SESSION['nombre'],$_SESSION['clave'],$_SESSION['correo']);
break;
case 2:
$op2=$operacion->registrar($_SESSION['nombre'],$_SESSION['clave'],$_SESSION['correo']);
break;
case 3:
$op3=$operacion->Cerrar($_SESSION['nombre'],$_SESSION['clave'],$_SESSION['correo']);
break;
}
echo "<br>
<br>
<a href='opcion.php'>Ir al principio</a>";
}
else
{
echo "<br>
<br>
<a href='siguiente.php'>Lo sentimos su correo, clave y contrasenia son incorrectos...</a>";
}
?>

Y SINO INICIA INCORRECTO MUESTRA ESTO

<html>
<?php
session_start();
class Operacion {
var $Fecha;
var $Numero;
function iniciar($fecha,$numero){
echo "<br> Registrar <br>";
$this->Fecha=$fecha;
$this->Numero=$numero;
echo "<br> la fecha es : ".$this->Fecha." el umero de veces es ".$this->Numero;
}
}
$operacion= new Operacion(" Registrar <br>");
switch($opc)
{
case 1:
$op1=$operacion->iniciar(time(),$_SESSION['c']);
break;
}
?>

<html>
<head>
<title>Variables de sesion</title>
<meta http-equiv="Content-Type" Content="text/html; charset=UTF-8">
</head>
<body>
<?php
echo "Nombre de usuario :".$_SESSION['nombre'];
echo "<br><br>";
echo "La fecha :".date("c");
echo "<br><br>";
echo "Numero de intentos :".$_SESSION['c'];
if (isset($_SESSION["c"])) {
   $_SESSION["c"]++;
   }
else {
   $_SESSION["c"]=1;
   }
$contar=$_SESSION["c"];

echo "<br>
<br>
<a href='opcion.php'>Regresar al principio</a>";
?>

DEBER 23

FRANCISCO MUNOZ
CATEDRATICO Ing Juan Espinoza.

SUMAR, RESTAR, MULTIPLICAR, DIVIDIR CON CLASES

MENU.PHP
<html>
<?php
echo "<FORM ACTION='OPERACION.php' method='POST'>";
ECHO "<H1>MENU</H1>";
echo "<H3>1)<input type='submit' value='suma' name='suma'></H3>";
echo "<H3>2)<input type='submit' value='resta' name='resta'></H3>";
echo "<h3>3)<input type='submit' value='multiplicacion' name='multi'></H3>";
echo "<H3>4)<input type='submit' value='divicion' name='divi'></H3>";
echo "</form>";
if( isset($_POST['suma']))
{
echo "<FORM ACTION='OPERACION.php' method='POST'>";
echo "<H3><input type='submit'  value='sumar' name='sum'></H3>";
echo "</form>";
}
if( isset($_POST['resta']))
{
echo "<FORM ACTION='OPERACION.php' method='POST'>";
echo "<H3><input type='submit'  value='restar' name='res'></H3>";
}
if( isset($_POST['multi']))
{
echo "<FORM ACTION='OPERACION.php' method='POST'>";
echo "<H3><input type='submit'  value='multiplicar' name='mul'></H3>";
}
if( isset($_POST['divi']))
{
echo "<FORM ACTION='OPERACION.php' method='POST'>";
echo "<H3><input type='submit'  value='dividir' name='div'></H3>";
}
?>
</html>


CLASE PRINCIPAL CALCULAR
OPERACION.PHP
<?php
class calcula {
var $operacion;
var $numero1;
var $numero2;
var $resultado;
function sumar($xxnumero1,$xxnumero2) {
$this->resultado = $xxnumero1+$xxnumero2;
return $this->resultado;
}
function restar($xxnumero1,$xxnumero2) {
$this->resultado = $xxnumero1-$xxnumero2;
return $this->resultado;
}
function mult($xxnumero1,$xxnumero2) {
$this->resultado = $xxnumero1*$xxnumero2;
return $this->resultado;
}
function dividir($xxnumero1,$xxnumero2) {
$this->resultado = $xxnumero1/$xxnumero2;
return $this->resultado;
}

}
?>
<?php
include('MENU.php');
?>

<form name="form1" method="post" action="">
  <p>
    <label>
      <input type="text" name="numero1" id="MENU.php">
    </label>
<BR>
      <label>
      <select name="operacion" id="operacion">
        <option value="x">X</option>
        <option value="/">/</option>
        <option value="-">-</option>
        <option value="+">+</option>
      </select>
    </label>
<p>
<label>
    <input type="text" name="numero2" id="numero2">
</label>
</p>
  <p>
    <label>
      <input type="submit" name="ok" id="ok" value="Calcular">
    </label>
  </p>
</form>

AQUI LE VALIDO ANTES DE QUE REALIZE OPERACION
<?php
if(isset($_POST['ok'])) {
$num1 = $_POST['numero1'];
$num2 = $_POST['numero2'];
$varcalcu = new calcula();
if(is_numeric($num1) && is_numeric($num2)) {
switch ($_POST['operacion']) { /
case "+":
$varcalcu->sumar($num1,$num2);
break;
case "-":
$varcalcu->restar($num1,$num2);
break;
case "x":
$varcalcu->mult($num1,$num2);
break;
case "/":
$varcalcu->dividir($num1,$num2);
break;
}
echo $varcalcu->resultado;
} else {
echo"Los valores de los numeros deben ser númericos!";
}
}
?>