SlideShare uma empresa Scribd logo
VI Semana da Informática Biomédica - Daniel Bojczuk




                Desenvolvimento Web com
VI Semana da Informática Biomédica - Daniel Bojczuk




                            Introdução
• PHP: Hypertext Preprocessor
• Desenvolvimento de aplicações WEB
• Desenvolvimento de aplicações Desktop
          • PHP-GTK
• Linguagem interpretada
• Frameworks: CakePHP , XAJAX
VI Semana da Informática Biomédica - Daniel Bojczuk   Slide 3 de X




                          Como funciona ?
VI Semana da Informática Biomédica - Daniel Bojczuk




                       Estrutura do código
      <?
           // código php
      ?>


      <html>
      <body>
      <?
           // código php
      ?>
      </html>
      </body>
VI Semana da Informática Biomédica - Daniel Bojczuk




                       Estrutura do código
      <html>
      <body>
      <?
           // código php
      ?>
      <center> Alguma coisa escrita</center>
      <?
        // código php
      ?>
      </html>
      </body>
VI Semana da Informática Biomédica - Daniel Bojczuk




                                     Variáveis
     • Começam com $
               •   $string = “Daniel”; ou $string=‘Daniel’;
               •   $inteiro = 1;
               •   $boolean = true;
               •   $double = 2,312
     • Case sensitive
     • Concatenação de variáveis
               • $concatenado = $string.$inteiro.$double
VI Semana da Informática Biomédica - Daniel Bojczuk




                                  Constantes
     • define(string $name, mixed $value [, bool $case_sensitive]);

      <?
       define(“CONSTANTE1” , ”Esta é uma constante”);
       define(“CONSTANTE2” , 2008 , false);
       define(“CONSTANTE3” , 2,32);
       define(“CONSTANTE4” , false);

       echo CONSTANTE1.”n”;
       echo constante2;
      ?>



      Esta é uma constante
      2008
VI Semana da Informática Biomédica - Daniel Bojczuk



                                          Array
      <?
       $nomes = array ('Daniel', 'Karina', 'José');
       $nomes[] = “Lívia”;

        $idades = array ( “Daniel” => 22,
                          “Karina” => 29,
                          “José” => 54);
        $idades[“Livia”] = 21;

       $caracteristicas = array ( “Daniel” => array ( “Altura” => '1,82',
                                                      “Olhos” => “Castanhos”),
                                  “Karina” => array ( “Altura” => '1,65',
                                                      “Olhos” => “Castanhos”),
                                   “José” => array ( “Altura” => '1,72',
                                                     “Olhos” => “Verdes”)
                                   );
       print_r($nomes);
       print_r($idades).
       print_r($caracteristicas);
      ?>
VI Semana da Informática Biomédica - Daniel Bojczuk



                                          Array
      Array
      (
        [0] => Daniel
        [1] => Karina
        [2] => José
        [3] => Lívia
      )
      Array
      (
        [Daniel] => 22
        [Karina] => 29
        [José] => 54
        [Livia] => 21
      )
VI Semana da Informática Biomédica - Daniel Bojczuk


                                          Array
      Array
      (
        [Daniel] => Array
           (
             [Altura] => 1,82
             [Olhos] => Castanhos
           )

          [Karina] => Array
             (
               [Altura] => 1,65
               [Olhos] => Castanhos
             )
          [José] => Array
             (
               [Altura] => 1,72
               [Olhos] => Verdes
             )

      )
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          Array
      <?
      $idades = array ( “Daniel” => 22,
                         “Karina” => 29,
                         “José” => 54);
       //echo “A idade do Daniel é $idades['Daniel']”; // Erro de sintaxe
       echo “A idade do Daniel é {$idades['Daniel']}n”;

       $quantidade = count($idades);
       echo “O array tem $quantidade itens”;
      ?>



      A idade do Daniel é 22
      O array tem 3 itens
VI Semana da Informática Biomédica - Daniel Bojczuk




                                 Operadores
     • Operação
               • $variavel = 1; → recebe o valor de
               • $variavel ++; → incrementa em 1 a variável
               • $variavel--; → decrementa em 1 a variável
               • $variavel += 2; → soma 2 ao valor da variável
               • $variavel -= 2; → subtrai 2 ao valor da variável
               • $variavel .= “ é o numero da sorte”; → concatena o
                 texto à variável
               • $variavel = 3%2 → A variável recebe o resto da
                 divisão de 3 por 2
VI Semana da Informática Biomédica - Daniel Bojczuk




                                 Operadores
     • Comparação
               • == → igualdade
               • != → desigualdade
               • >, <, >=, <= → maior que, menor que, maior ou
                 igual a, menor ou igual a
     • Lógicos
               • ! → negação
               • && ou and → E
               • || ou or → OU
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Estruturas de controle

      <?
        // Exemplo de if
        if ($nome == “Daniel”) {
                 echo “Olá $nome”;
       } else if ($nome == “Karina”) {
                 echo “$nome, seu acesso é restrito.”;
       } else {
                 echo “Você não tem permissão nenhuma”;
       }
      ?>
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Estruturas de controle
      <?
        // Exemplo de switch
       switch ($nome) {
               case “Daniel”:
                        echo “Seja bem vindo!”;
                        break;
               case “Karina”:
                        echo “Você tem acesso restrito”;
                        break;
               default:
                        echo “Você não tem acesso”;
                        break;
        }

      ?>
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Estruturas de controle
      <?
       $numero = 1;
       while( $numero < 5 ) {
              echo $numero.”n”;
              $numero++;
       }

      ?>



      1
      2
      3
      4
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Estruturas de controle
      <?
       $numero = 5;
       do {
               echo $numero.”n”;
               $numero++;
       } while( $numero < 5 );

      ?>



      5
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Estruturas de controle
      <?
       for ($i = 1; $i < 5; $i++) {
                echo $i.”n”;
       }

      ?>




      1
      2
      3
      4
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Estruturas de controle
      <?
       $idades = array( “Daniel” => 22,
                        “Karina” => 29,
                        “Lívia” => 21);
       foreach ($idades as $chave => $valor) {
              echo “A idade do(a) $chave é $valor n”;
       }
      ?>



      A idade do(a) Daniel é 22
      A idade do(a) Karina é 29
      A idade do(a) Lívia é 21
VI Semana da Informática Biomédica - Daniel Bojczuk




                                  Exercício 1
    • Faça um programa que construa um vetor
      de 6 elementos numéricos aleatórios
      inteiros e mostre:
         – Quantidade e quais são os números pares
         – Quantidade e quais são os números impares


        Dica: Use a função rand([ int $minimo, int
           $maximo ]) para retornar um número
                        aleatório.
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
      <?
       $nome = “Daniel”;
       $nota = 10;

        $texto = “A nota do “.$nome.” é igual a “.$nota.”n”;
        $texto2 = “A nota do $nome é igual a $notan”;
        $texto3 = ‘A nota do $nome é igual a $notan’;

       echo $texto;
       echo $texto2;
       echo $texto3;
      ?>


      A nota do Daniel é igual a 10
      A nota do Daniel é igual a 10
      A nota do $nome é igual a $notan
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • trim(string $str [, string $charlist]);
          – “ “ – espaço normal
          – “t” – tabulação
          – “n” – quebra de linha
          – “r” – retorno de carro
          – “0” – byte NULL
          – “X0B”, tabulalção vertical
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • trim(string $str [, string $charlist]);

      <?
       $texto = “       Ola, este é um texto de teste ...   “;
       $resultado1 = trim($texto);
       $resultado2 = trim($texto,’t.’);

       echo $resultado1.”n”.$resultado2;
      ?>



      Ola, este é um texto de teste ...
      Ola, este é um texto de teste
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • strpos(string $texto, mixed $parte [, int $offset]);
      <?
       $texto = “abcdefg abcdefg”;
       $posicao1 = strpos($texto,”a”);
       $posicao2 = strpos($texto,”a”,1);

       echo $posicao1.”n”;
       echo $posicao2;
      ?>


      0
      8
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • substr( string $str, int $start [,int $length]);
      <?
       $texto = “Meu nome é Daniel”;
       $trecho1 = substr($texto, 0);
       $trecho2 = substr($texto,4);
       $trecho3 = substr($texto,4,strpos($texto,“é”));

       echo $trecho1.”n”;
       echo $trecho2.”n”;
       echo $trecho3;
      ?>


      Meu nome é Daniel
      nome é Daniel
      nome é Da
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • strlen(string $texto);
      <?
       $texto = “Meu nome é Daniel”;
       $tamanho = strlen($texto);
       echo $tamanho;
      ?>


       17
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • str_replace(mixed $search, mixed $replace, mixed
       $subject [, int $count]);

      <?
       $texto = “Meu nome é Daniel e o da minha mãe é Regina”;
       $textoAlterado = str_replace(“Meu”, “Seu”, $texto);
       $textoAlterado2 = str_replace(“é”, “não é” , $texto, $qtde);

       echo $textoAlterado.”n”;
       echo $textoAlterado2.”n”;
       echo “Foram alterado $qtde vezes”;
      ?>


      Seu nome é Daniel e o da minha mãe é Regina
      Meu nome não é Daniel e o da minha mãe não é Regina
      Foram alterado 2 vezes
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • explode( string $delimiter, string $string [,int $limit]);
     • list ( mixed $varname [, mixed $...]);

      <?
       $texto = “Daniel Antonio Fernandes Bojczuk”;
       $array1 = explode(“ “, $texto);
       list($primeiroNome, $resto) = explode(“ “,$texto,2);

        print_r($array1);
        echo “n”.$primeiroNome.”n”;
        echo $resto;

      ?>
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • explode( string $delimiter, string $string [,int $limit]);
     • list ( mixed $varname [, mixed $...]);

      Array
      (
        [0] => Daniel
        [1] => Antonio
        [2] => Fernandes
        [3] => Bojczuk
      )

      Daniel
      Antonio Fernandes Bojczuk
VI Semana da Informática Biomédica - Daniel Bojczuk




                                          String
     • implode( string $glue, array $pieces);

      <?
       $pedacos = array (‘Daniel’, ‘Antonio’, ‘Fernandes’, ‘Bojczuk’);

        $nome = implode (“ “, $pedacos);

       echo $nome;
      ?>



      Daniel Antonio Fernandes Bojczuk
VI Semana da Informática Biomédica - Daniel Bojczuk




                                  Exercício 2
    • Faça um script que inverta a ordem das
      palavras de uma frase.

     Dica: Utiliza a função krsort($array) para inverter a
               ordem dos elementos de um array.
VI Semana da Informática Biomédica - Daniel Bojczuk




                                  Exercício 3
    • Faça um script que conte o número de
      vogais (maiúsculas ou minusculas)
      existentes em uma frase. Desconsidere os
      acentos.

        Dica: Use a função in_array($elemento, $array)
            para procurar um elemento em um array.
           Dica: Use strtoupper($string) caso precise
         transformar uma string para letras maiúsculas.
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Formulários com PHP
     • POST
          – Envio pelo cabeçalho da página
      <form action=”formulario.php” method=”POST”>


     • GET
          – Envio pela URL da página
      <form action=”formulario.php” method=”GET”>
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Formulários com PHP
      <html>
      <body>
      <form action=”formulario.php” method=”POST”>
      Nome: <input type=”text” name=”usuario” size=”20” maxlength=”50”><br>
      Senha:<input type=”password” name=”senha” size=”8” maxlength=”8”><br>
      <input type=”submit” value=”Entrar”>
      </body>
      </html>

      <?
       print_r($_POST);

        echo “O nome do usuário é {$_POST['usuario']}n”;
        echo “A senha é {$_POST['senha']}”;

      ?>
VI Semana da Informática Biomédica - Daniel Bojczuk




                   Formulários com PHP
      <?
       if (empty($_POST)) {
      ?>
      <html>
      <body>
      <form action=”<?=htmlentities($_SERVER['PHP_SELF']) ?>” method=”POST”>
      Nome: <input type=”text” name=”usuario” size=”20” maxlength=”50”><br>
      Senha:<input type=”password” name=”senha” size=”8” maxlength=”8”><br>
      <input type=”submit” value=”Entrar”>
      </body>
      </html>
      <?
       } else {
                print_r($_POST);

                echo “O nome do usuário é {$_POST['usuario']}n”;
                echo “A senha é {$_POST['senha']}”;
      }
      ?>
VI Semana da Informática Biomédica - Daniel Bojczuk




                                  Exercício 4
    • Valide um formulário de usuário e senha da
      seguinte forma:
         – Username: Não pode estar em branco
         – Senha: Deve ter no mínimo 4 caracteres, tendo
           no mínimo um dos caracteres abaixo:
              !@#$%&*

         Caso não satisfaça a condição, exiba uma
          mensagem de erro.
Variáveis de Sessão
• Iniciar sessão – gera um SID da máquina
  cliente.
    • session_start();
• Estabelecer e usar variáveis de sessão
    • $_SESSION['nome'] = “Daniel”;
    • echo $_SESSION['nome'];
• Encerrar a sessão.
    • session_destroy();
Conexão com Banco de Dados
VI Semana da Informática Biomédica - Daniel Bojczuk




      Orientação a objetos com PHP

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Curso php

  • 1. VI Semana da Informática Biomédica - Daniel Bojczuk Desenvolvimento Web com
  • 2. VI Semana da Informática Biomédica - Daniel Bojczuk Introdução • PHP: Hypertext Preprocessor • Desenvolvimento de aplicações WEB • Desenvolvimento de aplicações Desktop • PHP-GTK • Linguagem interpretada • Frameworks: CakePHP , XAJAX
  • 3. VI Semana da Informática Biomédica - Daniel Bojczuk Slide 3 de X Como funciona ?
  • 4. VI Semana da Informática Biomédica - Daniel Bojczuk Estrutura do código <? // código php ?> <html> <body> <? // código php ?> </html> </body>
  • 5. VI Semana da Informática Biomédica - Daniel Bojczuk Estrutura do código <html> <body> <? // código php ?> <center> Alguma coisa escrita</center> <? // código php ?> </html> </body>
  • 6. VI Semana da Informática Biomédica - Daniel Bojczuk Variáveis • Começam com $ • $string = “Daniel”; ou $string=‘Daniel’; • $inteiro = 1; • $boolean = true; • $double = 2,312 • Case sensitive • Concatenação de variáveis • $concatenado = $string.$inteiro.$double
  • 7. VI Semana da Informática Biomédica - Daniel Bojczuk Constantes • define(string $name, mixed $value [, bool $case_sensitive]); <? define(“CONSTANTE1” , ”Esta é uma constante”); define(“CONSTANTE2” , 2008 , false); define(“CONSTANTE3” , 2,32); define(“CONSTANTE4” , false); echo CONSTANTE1.”n”; echo constante2; ?> Esta é uma constante 2008
  • 8. VI Semana da Informática Biomédica - Daniel Bojczuk Array <? $nomes = array ('Daniel', 'Karina', 'José'); $nomes[] = “Lívia”; $idades = array ( “Daniel” => 22, “Karina” => 29, “José” => 54); $idades[“Livia”] = 21; $caracteristicas = array ( “Daniel” => array ( “Altura” => '1,82', “Olhos” => “Castanhos”), “Karina” => array ( “Altura” => '1,65', “Olhos” => “Castanhos”), “José” => array ( “Altura” => '1,72', “Olhos” => “Verdes”) ); print_r($nomes); print_r($idades). print_r($caracteristicas); ?>
  • 9. VI Semana da Informática Biomédica - Daniel Bojczuk Array Array ( [0] => Daniel [1] => Karina [2] => José [3] => Lívia ) Array ( [Daniel] => 22 [Karina] => 29 [José] => 54 [Livia] => 21 )
  • 10. VI Semana da Informática Biomédica - Daniel Bojczuk Array Array ( [Daniel] => Array ( [Altura] => 1,82 [Olhos] => Castanhos ) [Karina] => Array ( [Altura] => 1,65 [Olhos] => Castanhos ) [José] => Array ( [Altura] => 1,72 [Olhos] => Verdes ) )
  • 11. VI Semana da Informática Biomédica - Daniel Bojczuk Array <? $idades = array ( “Daniel” => 22, “Karina” => 29, “José” => 54); //echo “A idade do Daniel é $idades['Daniel']”; // Erro de sintaxe echo “A idade do Daniel é {$idades['Daniel']}n”; $quantidade = count($idades); echo “O array tem $quantidade itens”; ?> A idade do Daniel é 22 O array tem 3 itens
  • 12. VI Semana da Informática Biomédica - Daniel Bojczuk Operadores • Operação • $variavel = 1; → recebe o valor de • $variavel ++; → incrementa em 1 a variável • $variavel--; → decrementa em 1 a variável • $variavel += 2; → soma 2 ao valor da variável • $variavel -= 2; → subtrai 2 ao valor da variável • $variavel .= “ é o numero da sorte”; → concatena o texto à variável • $variavel = 3%2 → A variável recebe o resto da divisão de 3 por 2
  • 13. VI Semana da Informática Biomédica - Daniel Bojczuk Operadores • Comparação • == → igualdade • != → desigualdade • >, <, >=, <= → maior que, menor que, maior ou igual a, menor ou igual a • Lógicos • ! → negação • && ou and → E • || ou or → OU
  • 14. VI Semana da Informática Biomédica - Daniel Bojczuk Estruturas de controle <? // Exemplo de if if ($nome == “Daniel”) { echo “Olá $nome”; } else if ($nome == “Karina”) { echo “$nome, seu acesso é restrito.”; } else { echo “Você não tem permissão nenhuma”; } ?>
  • 15. VI Semana da Informática Biomédica - Daniel Bojczuk Estruturas de controle <? // Exemplo de switch switch ($nome) { case “Daniel”: echo “Seja bem vindo!”; break; case “Karina”: echo “Você tem acesso restrito”; break; default: echo “Você não tem acesso”; break; } ?>
  • 16. VI Semana da Informática Biomédica - Daniel Bojczuk Estruturas de controle <? $numero = 1; while( $numero < 5 ) { echo $numero.”n”; $numero++; } ?> 1 2 3 4
  • 17. VI Semana da Informática Biomédica - Daniel Bojczuk Estruturas de controle <? $numero = 5; do { echo $numero.”n”; $numero++; } while( $numero < 5 ); ?> 5
  • 18. VI Semana da Informática Biomédica - Daniel Bojczuk Estruturas de controle <? for ($i = 1; $i < 5; $i++) { echo $i.”n”; } ?> 1 2 3 4
  • 19. VI Semana da Informática Biomédica - Daniel Bojczuk Estruturas de controle <? $idades = array( “Daniel” => 22, “Karina” => 29, “Lívia” => 21); foreach ($idades as $chave => $valor) { echo “A idade do(a) $chave é $valor n”; } ?> A idade do(a) Daniel é 22 A idade do(a) Karina é 29 A idade do(a) Lívia é 21
  • 20. VI Semana da Informática Biomédica - Daniel Bojczuk Exercício 1 • Faça um programa que construa um vetor de 6 elementos numéricos aleatórios inteiros e mostre: – Quantidade e quais são os números pares – Quantidade e quais são os números impares Dica: Use a função rand([ int $minimo, int $maximo ]) para retornar um número aleatório.
  • 21. VI Semana da Informática Biomédica - Daniel Bojczuk String <? $nome = “Daniel”; $nota = 10; $texto = “A nota do “.$nome.” é igual a “.$nota.”n”; $texto2 = “A nota do $nome é igual a $notan”; $texto3 = ‘A nota do $nome é igual a $notan’; echo $texto; echo $texto2; echo $texto3; ?> A nota do Daniel é igual a 10 A nota do Daniel é igual a 10 A nota do $nome é igual a $notan
  • 22. VI Semana da Informática Biomédica - Daniel Bojczuk String • trim(string $str [, string $charlist]); – “ “ – espaço normal – “t” – tabulação – “n” – quebra de linha – “r” – retorno de carro – “0” – byte NULL – “X0B”, tabulalção vertical
  • 23. VI Semana da Informática Biomédica - Daniel Bojczuk String • trim(string $str [, string $charlist]); <? $texto = “ Ola, este é um texto de teste ... “; $resultado1 = trim($texto); $resultado2 = trim($texto,’t.’); echo $resultado1.”n”.$resultado2; ?> Ola, este é um texto de teste ... Ola, este é um texto de teste
  • 24. VI Semana da Informática Biomédica - Daniel Bojczuk String • strpos(string $texto, mixed $parte [, int $offset]); <? $texto = “abcdefg abcdefg”; $posicao1 = strpos($texto,”a”); $posicao2 = strpos($texto,”a”,1); echo $posicao1.”n”; echo $posicao2; ?> 0 8
  • 25. VI Semana da Informática Biomédica - Daniel Bojczuk String • substr( string $str, int $start [,int $length]); <? $texto = “Meu nome é Daniel”; $trecho1 = substr($texto, 0); $trecho2 = substr($texto,4); $trecho3 = substr($texto,4,strpos($texto,“é”)); echo $trecho1.”n”; echo $trecho2.”n”; echo $trecho3; ?> Meu nome é Daniel nome é Daniel nome é Da
  • 26. VI Semana da Informática Biomédica - Daniel Bojczuk String • strlen(string $texto); <? $texto = “Meu nome é Daniel”; $tamanho = strlen($texto); echo $tamanho; ?> 17
  • 27. VI Semana da Informática Biomédica - Daniel Bojczuk String • str_replace(mixed $search, mixed $replace, mixed $subject [, int $count]); <? $texto = “Meu nome é Daniel e o da minha mãe é Regina”; $textoAlterado = str_replace(“Meu”, “Seu”, $texto); $textoAlterado2 = str_replace(“é”, “não é” , $texto, $qtde); echo $textoAlterado.”n”; echo $textoAlterado2.”n”; echo “Foram alterado $qtde vezes”; ?> Seu nome é Daniel e o da minha mãe é Regina Meu nome não é Daniel e o da minha mãe não é Regina Foram alterado 2 vezes
  • 28. VI Semana da Informática Biomédica - Daniel Bojczuk String • explode( string $delimiter, string $string [,int $limit]); • list ( mixed $varname [, mixed $...]); <? $texto = “Daniel Antonio Fernandes Bojczuk”; $array1 = explode(“ “, $texto); list($primeiroNome, $resto) = explode(“ “,$texto,2); print_r($array1); echo “n”.$primeiroNome.”n”; echo $resto; ?>
  • 29. VI Semana da Informática Biomédica - Daniel Bojczuk String • explode( string $delimiter, string $string [,int $limit]); • list ( mixed $varname [, mixed $...]); Array ( [0] => Daniel [1] => Antonio [2] => Fernandes [3] => Bojczuk ) Daniel Antonio Fernandes Bojczuk
  • 30. VI Semana da Informática Biomédica - Daniel Bojczuk String • implode( string $glue, array $pieces); <? $pedacos = array (‘Daniel’, ‘Antonio’, ‘Fernandes’, ‘Bojczuk’); $nome = implode (“ “, $pedacos); echo $nome; ?> Daniel Antonio Fernandes Bojczuk
  • 31. VI Semana da Informática Biomédica - Daniel Bojczuk Exercício 2 • Faça um script que inverta a ordem das palavras de uma frase. Dica: Utiliza a função krsort($array) para inverter a ordem dos elementos de um array.
  • 32. VI Semana da Informática Biomédica - Daniel Bojczuk Exercício 3 • Faça um script que conte o número de vogais (maiúsculas ou minusculas) existentes em uma frase. Desconsidere os acentos. Dica: Use a função in_array($elemento, $array) para procurar um elemento em um array. Dica: Use strtoupper($string) caso precise transformar uma string para letras maiúsculas.
  • 33. VI Semana da Informática Biomédica - Daniel Bojczuk Formulários com PHP • POST – Envio pelo cabeçalho da página <form action=”formulario.php” method=”POST”> • GET – Envio pela URL da página <form action=”formulario.php” method=”GET”>
  • 34. VI Semana da Informática Biomédica - Daniel Bojczuk Formulários com PHP <html> <body> <form action=”formulario.php” method=”POST”> Nome: <input type=”text” name=”usuario” size=”20” maxlength=”50”><br> Senha:<input type=”password” name=”senha” size=”8” maxlength=”8”><br> <input type=”submit” value=”Entrar”> </body> </html> <? print_r($_POST); echo “O nome do usuário é {$_POST['usuario']}n”; echo “A senha é {$_POST['senha']}”; ?>
  • 35. VI Semana da Informática Biomédica - Daniel Bojczuk Formulários com PHP <? if (empty($_POST)) { ?> <html> <body> <form action=”<?=htmlentities($_SERVER['PHP_SELF']) ?>” method=”POST”> Nome: <input type=”text” name=”usuario” size=”20” maxlength=”50”><br> Senha:<input type=”password” name=”senha” size=”8” maxlength=”8”><br> <input type=”submit” value=”Entrar”> </body> </html> <? } else { print_r($_POST); echo “O nome do usuário é {$_POST['usuario']}n”; echo “A senha é {$_POST['senha']}”; } ?>
  • 36. VI Semana da Informática Biomédica - Daniel Bojczuk Exercício 4 • Valide um formulário de usuário e senha da seguinte forma: – Username: Não pode estar em branco – Senha: Deve ter no mínimo 4 caracteres, tendo no mínimo um dos caracteres abaixo: !@#$%&* Caso não satisfaça a condição, exiba uma mensagem de erro.
  • 37. Variáveis de Sessão • Iniciar sessão – gera um SID da máquina cliente. • session_start(); • Estabelecer e usar variáveis de sessão • $_SESSION['nome'] = “Daniel”; • echo $_SESSION['nome']; • Encerrar a sessão. • session_destroy();
  • 38. Conexão com Banco de Dados
  • 39. VI Semana da Informática Biomédica - Daniel Bojczuk Orientação a objetos com PHP