Es mostren els missatges amb l'etiqueta de comentaris PHP. Mostrar tots els missatges
Es mostren els missatges amb l'etiqueta de comentaris PHP. Mostrar tots els missatges

dimecres, 30 de setembre del 2015

PHP. Operadors

Operadors PHP

Els operadors s'utilitzen per a realitzar operacions sobre les variables i valors.
PHP divideix els operadors en els següents grups:
  • Els operadors aritmètics
  • Operadors d'assignació
  • Els operadors de comparació
  • Operadors d'increment / decrement
  • Els operadors lògics
  • Operadors de Strings
  • Operadors d'Arrays
Aritmètics
Operator
Name
Example
Result
+
Addition
$x + $y
Sum of $x and $y
-
Subtraction
$x - $y
Difference of $x and $y
*
Multiplication
$x * $y
Product of $x and $y
/
Division
$x / $y
Quotient of $x and $y
%
Modulus
$x % $y
Remainder of $x divided by $y
**
Exponentiation
$x ** $y
Result of raising $x to the $y'th power (Introduced in PHP 5.6)
Assignació

Assignment
Same as...
Description
x = y
x = y
The left operand gets set to the value of the expression on the right
x += y
x = x + y
Addition
x -= y
x = x - y
Subtraction
x *= y
x = x * y
Multiplication
x /= y
x = x / y
Division
x %= y
x = x % y
Modulus
Comparació

Operator
Name
Example
Result
==
Equal
$x == $y
Returns true if $x is equal to $y
===
Identical
$x === $y
Returns true if $x is equal to $y, and they are of the same type
!=
Not equal
$x != $y
Returns true if $x is not equal to $y
<> 
Not equal
$x <> $y
Returns true if $x is not equal to $y
!==
Not identical
$x !== $y
Returns true if $x is not equal to $y, or they are not of the same type
> 
Greater than
$x > $y
Returns true if $x is greater than $y
< 
Less than
$x < $y
Returns true if $x is less than $y
>=
Greater than or equal to
$x >= $y
Returns true if $x is greater than or equal to $y
<=
Less than or equal to
$x <= $y
Returns true if $x is less than or equal to $y



Increment/Decrement

Operator
Name
Description
++$x
Pre-increment
Increments $x by one, then returns $x
$x++
Post-increment
Returns $x, then increments $x by one
--$x
Pre-decrement
Decrements $x by one, then returns $x
$x--
Post-decrement
Returns $x, then decrements $x by one



Lògics

Operator
Name
Example
Result
and
And
$x and $y
True if both $x and $y are true
or
Or
$x or $y
True if either $x or $y is true
xor
Xor
$x xor $y
True if either $x or $y is true, but not both
&&
And
$x && $y
True if both $x and $y are true
||
Or
$x || $y
True if either $x or $y is true
!
Not
!$x
True if $x is not true

String

Operator
Name
Example
Result
.
Concatenation
$txt1 . $txt2
Concatenation of $txt1 and $txt2
.=
Concatenation assignment
$txt1 .= $txt2
Appends $txt2 to $txt1
Arrays
Operator
Name
Example
Result
+
Union
$x + $y
Union of $x and $y
==
Equality
$x == $y
Returns true if $x and $y have the same key/value pairs
===
Identity
$x === $y
Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!=
Inequality
$x != $y
Returns true if $x is not equal to $y
<> 
Inequality
$x <> $y
Returns true if $x is not equal to $y
!==
Non-identity
$x !== $y
Returns true if $x is not identical to $y



dijous, 24 de setembre del 2015

PHP. Tipus de dades

Les variables poden emmagatzemar dades de diferents tipus, i els diferents tipus de dades es poden fer coses diferents i aplicar funcions diferents.

PHP suporta els següents tipus de dades:
  • String (cadenes)
Una cadena és una seqüència de caràcters, com "Hola, món!".
Una cadena pot ser qualsevol text entre cometes. Es pot utilitzar cometes simples o dobles
  • Integer (numèric, sense decimals)
Un sencer és un nombre sencer (sense decimals). És un nombre entre -2147483648 i 2147483647.
Regles per als nombres enters:
  • Un sencer ha de tenir almenys un dígit (0-9)
  • Un sencer no pot contenir espais en blanc o comes
  • Un sencer no ha de tenir un punt decimal
  • Un sencer pot ser positiu o negatiu
  • Els sencers poden ser especificats en tres formats: decimal (basat 10), hexadecimal (16-basada - el prefix 0x) o octal (8-basat - prefix 0)
  • Float (nombres de punt flotant - també anomenada double)
És un nombre amb un punt decimal o un nombre en forma exponencial.
  • Boolean
Booleà representa dos estats possibles: vertader o fals. (true o false)
  • Matriu (Arrays) o Vectors
  • Objecte
  • NULL
Null és un tipus de dades especial que només pot tenir un valor de: NULL.
Una variable de tipus de dades NULL és una variable que no té cap valor assignat.
Consell: Si es crea una variable sense un valor, se li assigna automàticament un valor de NULL.
  • Recursos
La funció var_dump PHP () retorna el tipus de dades i el valor:

<?php 
$x = 10.365;
var_dump($x);
?>
La funció ens retorna:

float(10.365)

dimarts, 9 de desembre del 2014

Porcesar formularis en un sol document


Fins ara hem enviat el resultat del formulari en un altre document. En aquest exemple, ho farem que sempre s’envia a la mateixa pàgina

La forma habitual de treballar amb formularis en PHP és utilitzar un únic programa que processi el formulari o el mostri segons hagi estat o no enviat, respectivament

Quin són els avantatges:

  • Disminueix el nombre de fitxers
  • Permet validar les dades del formulari en el propi formulari
Quin és el procediment:

si s'ha enviat el formulari:

//cas b
    processar formulari
si no:

//cas a
     Mostra formulari
fsi



La 1 ª vegada que es carrega la pàgina es mostra el formulari (a)
La 2 ª vegada es processa el formulari (b)
Per saber si s'ha enviat el formulari s'acudeix a la variable corresponent al botó d'enviament. Si aquest botó apareix de la manera següent en el formulari HTML:

<INPUT TYPE="SUBMIT" NAME="enviar" VALUE="procesar">

llavors la condició anterior es transforma en:

if (isset($_REQUEST['enviar']))

o bé


if ($_REQUEST['enviar'] == "processar")

Exemple:
Supossem que tenim el següent formulari:

 
 Supossem el següent codi:

<html>
<head>
 
  <title>Exemple 1</title>

</head>

<body>

<?PHP
   if (isset($_REQUEST['Enviar']))
   {
   echo "Su edad es : <br>";
   echo $_REQUEST['edad']."<br>";
   echo "<A HREF='formulari1.php'>Volver a responder</A>";
   }
   else {
   
   ?>
   
   

<form action="formulari1.php" method="post">
  <h1>Formulari 1</h1>
  <fieldset>
 <legend>Formulario</legend>

 <p>Indique su edad:</p>
 <p><strong>Edad:</strong>
 <select name="edad">
   <option selected="selected"></option>
   <option value="Menos de 20 años">Menos de 20 años</option>
   <option value="Entre 20 y 39 años">Entre 20 y 39 años</option>
   <option value="Entre 40 y 59 años">Entre 40 y 59 años</option>
   <option value="60 años o más">60 años o más</option>
 </select></p>

 <p>
 <input type="submit" value="Enviar" name="Enviar" />
 <input type="reset" value="Borrar" name="Reset" /></p>
  </fieldset>
</form>
<?PHP
   }
?>
</body>
</html>


Ara ho complicarem una mica més. En primer lloc, afegim css per millorar el formulari:

<style type="text/css">

 /* General */
BODY {font-family: verdana,arial, sans-serif; font-size: 10pt;}
/* Contenido */
H1 {font-size: 16pt; font-weight: bold; color: #0066CC;}

H2 {font-size: 12pt; font-weight: bold; font-style: italic; color: black;}
H3 {font-size: 10pt; font-weight: bold; color: black;}
/* Formulario */
FORM.borde {border: 1px dotted #0066CC; padding: 0.5em 0.2em; width: 80%;} 

FORM P {clear: left; margin: 0.2em; padding: 0.1em;}
FORM P LABEL {float: left; width: 25%; font-weight: bold;}
.error {color: red;}
</style>


I ara el que farem és que quan doni error afegirem un missatge al costat del camp . Per saber si dona error, en primer lloc haurem de validar si ha pulsat el botó de buscar. Si és així, i hi ha un error muntem un array amb el missatge: 



if ($errores["edad"]!=""){
  echo "<span class='error'>".$errores["edad"]."</span>";





 Codi sencer :

<html>
<head>
 
  <title>Exemple 1</title>
   <style type="text/css">
     /* General */
     BODY {font-family: verdana,arial, sans-serif; font-size: 10pt;}

     /* Contenido */
     H1 {font-size: 16pt; font-weight: bold; color: #0066CC;}
     H2 {font-size: 12pt; font-weight: bold; font-style: italic; color: black;}
     H3 {font-size: 10pt; font-weight: bold; color: black;}
        
     /* Formulario */
     FORM.borde {border: 1px dotted #0066CC; padding: 0.5em 0.2em; width: 80%;}
     FORM P {clear: left; margin: 0.2em; padding: 0.1em;}
     FORM P LABEL {float: left; width: 25%; font-weight: bold;}
     .error {color: red;}

   </style>

</head>

<body>

<?PHP

// Obtener valores introducidos en el formulario

   if (isset($_REQUEST['edad']))
   {
     $edad = $_REQUEST['edad'];
   }
   else {
     $edad="";
   }
   
// Comprobar errores
   $error = false;
   $errores["edad"] = "";
   if (isset($_REQUEST['Enviar']))
   {
      // Texto de búsqueda
   if (trim($edad) == "")
   {
      $errores["edad"] = "¡Debe introducir su edad!";
      $error = true;
   }
    
   }
   
 if (isset($_REQUEST['Enviar']) && $error==false) {
    echo "Su edad es : <br>";
    echo $_REQUEST['edad']."<br>";
    echo "<A HREF='formulari3.php'>Volver a responder</A>";
   }
   else {
   
   ?>
   
   

<form action="formulari3.php" method="post">
  <h1>Formulari 3</h1>
  <fieldset>
 <legend>Formulario 3</legend>

 <p>Indique su edad:</p>
 <p><strong>Edad:</strong>
 <select name="edad">
   <option selected="selected"></option>
   <option value="Menos de 20 años">Menos de 20 años</option>
   <option value="Entre 20 y 39 años">Entre 20 y 39 años</option>
   <option value="Entre 40 y 59 años">Entre 40 y 59 años</option>
   <option value="60 años o más">60 años o más</option>
 </select></p>
    
    <?PHP
 if ($errores["edad"]!=""){
   echo "<span class='error'>".$errores["edad"]."</span>";
    }
    ?>
    <p>
 <input type="submit" value="Enviar" name="Enviar" />
 <input type="reset" value="Borrar" name="Reset" /></p>
  </fieldset>
</form>
<?PHP
   }
?>
</body>
</html>