switch case to work when migrating from PHP 5.6 to 7.0

Asked

Viewed 132 times

1

I have a news system running with PHP 5.3 and would like to upgrade it to at least 5.6.

I have been using Php_codesniffer-master and Phpcompatibility-master to assist me in the change. Most of the problems encountered were simple, just replace mysql_query for mysqli_query.

I ask for help to solve the problem of the news no longer being aired, and I believe the problem is related to the line while ($coluna = @mysqli_fetch_array($query)){ of the code below, because in phpcs it shows the following error:

Expected "while (...) { n"; found "while (...){ n

<?php
header('Content-Type: text/html; charset=iso-8859-1');
require "include/conexao.php";
// ------- aqui sera implementada nossa proposta ------ //
// neste momento estamos montando o comando sql para
// podermos selecionar os dados de nossa tabela no banco de dados
$sql = "SELECT * FROM noticias";
// agora utilizando a ultima funcao apresentada, faremos a
// execucao consequentemente sera criada a nossa tabela
$query = @mysqli_query($conn, $sql);
// note que novamente foi utilizado o @(arroba) a frente da funcao
// agora faremos um teste para verificar se a funcao mysqli_query
// foi bem sucedida
if (!$query) {
    die("Problemas ao executar o sql !!!");
} else {
    // neste ponto, faremos o tratamento das informacoes retornadas
    // pela execucao do sql de selecao de dados
    while ($coluna = @mysqli_fetch_array($query)){
        // esta atribuicao de coluna["coluna_da_tabela"] a uma
        // variavel se da pelo fato apenas de simplificar o
        // entendimento do que esta se fazendo
        $id = $coluna["id"];
        $categoria = $coluna["categoria"];
        $subtitulo = $coluna["subtitulo"];
        $texto = $coluna["texto"];
        $fonte = $coluna["fonte"];
        $fonte_foto = $coluna["fonte_foto"];
        $data = $coluna["data"];
        $hora = $coluna["hora"];
        $dstq = $coluna["dstq"];
        $foto0 = $coluna["foto0"];
        $foto1 = $coluna["foto1"];
        $foto2 = $coluna["foto2"];
        $foto3 = $coluna["foto3"];
        $foto4 = $coluna["foto4"];
        $titulo = $coluna["titulo"];
        $titulo = stripslashes($titulo);
        $subtitulo = stripslashes($subtitulo);
        $texto = stripslashes($texto);

        // agora atraves do comando echo pertencente ao PHP
        // iremos apresentar os dados selecionados, na tela
        switch ($noticia) {
        case "$id":
            ?>
<html>aqui vai minha página, tirei pois acho que o problema não está aqui

 <?php

            break;
        }
    }
}

?>          
</html>

Follows code from conexao.php:

<?

/* informações para conexão à base de dados */

$host = "pirapongadomato.com";  // host do mysqli
$user = "user";       // usuário
$pass = "pass";     // senha do usuário
$base = "piraponga"; // nome da base de dados

// conecta o mysqli
$conn = mysqli_connect($host, $user, $pass, $base) or die ("<br><br><center>Problemas ao conectar no servidor: " . mysqli_error() . "</center>");
// seleciona a base de dados
//código original: $banc = mysql_select_db($base) or die ("<br><br><center>Problemas ao selecionar a base de dados do sistemas: " . mysql_error() . "</center>");
$banc = mysqli_connect($host, $user, $pass, $base) or die ("<br><br><center>Problemas ao selecionar a base de dados do sistemas: " . mysqli_error() . "</center>");
?>

What do you think it could be?

Edit: follows Cód. html:

<html lang="pt-br">
<head>    
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META NAME="description" CONTENT="<?php echo "$subtitulo "; ?>" >
<META NAME="keywords" CONTENT="Piraponga, projeto, montagem, manutencao,eletrica">
<link rel="shortcut icon" href="../../../images/Piraponga.ico">
<meta name="robots" content="index, follow">
<title>Piraponga - <?php echo $titulo; ?></title>

<!-- ######################Codigo css da pagina #############################-->
<link rel="stylesheet" type="text/css" href="../../../estilo/index.css">
<!-- ######################Código css dos menus #############################-->
<link rel="stylesheet" type="text/css" href="../../../estilo/menu_index.css">
<link rel="stylesheet" type="text/css" href="../../../estilo/menu_top.css">
<!-- Efeito LightBox -->
<script src="../../../lightbox/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="../../../lightbox/js/lightbox.min.js" type="text/javascript"></script> 
<!-- <script src="lightbox/js/custom-lightbox.js" type="text/javascript"></script> -->
<link rel="stylesheet" type="text/css" href="../../../lightbox/css/lightbox.css">
<!-- Fim do efeito LightBox -->
<!--#######################Script de compatibilidade windows phone 8 | IE 10####-->
<script type="text/javascript">if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
  var msViewportStyle = document.createElement('style')
  msViewportStyle.appendChild(
    document.createTextNode(
      '@-ms-viewport{width:auto!important}'
    )
  )
  document.querySelector('head').appendChild(msViewportStyle)
}</script>
<script type="text/javascript">
function TamFonte(num, id)
{
    document.getElementById(id).className = "ft"+num;
}
</script>

<style type="text/css">
#noticia { text-align: justify; }
.ft1 { font-family: 'trebuchet ms'; font-size: 13px; color: #000000; text-decoration: none; }
.ft1:hover { color: #000000; text-decoration: none; }
.ft1:visited { color: #000000; text-decoration: none; }
.ft2 { font-family: 'trebuchet ms'; font-size: 15px; color: #000000; text-decoration: none; }
.ft2:hover { color: #000000; text-decoration: none; }
.ft2:visited { color: #000000; text-decoration: none; }
.ft3 { font-family: 'trebuchet ms'; font-size: 17px; color: #000000; text-decoration: none; }
.ft3:hover { color: #000000; text-decoration: none; }
.ft3:visited { color: #000000; text-decoration: none; }
</style>


    <!-- Bootstrap -->
    <link href="../../../css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../../../css/font-awesome.min.css">
    <!-- Custom styles for this template -->
    <link href="../../../css/dashboard.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="../../../js/respond.min.js"></script>
    <script src="../../../js/html5shiv.min.js"></script>
    <![endif]-->
</head>

<body>
<!--[if lt IE 9]>
<div class="alert alert-warning" role="alert">ATEN??O! Seu navegador ? antigo, 
    sugerimos o uso do Firefox ou outro navegador mais atual para poder 
    visualizar esta p?gina melhor</div>
<![endif]-->
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.5";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div id="wrap">
    <div id="header">

            <nav class="navbar navbar-default navbar-fixed-top">

            <div class="container" id="menu_top">    

                <div class="navbar-header">
                     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                       <span class="sr-only">Toggle navigation</span>
                      <span class="icon-bar"></span>
                       <span class="icon-bar"></span>
                       <span class="icon-bar"></span>
                      </button>
                      <a class="navbar-brand" id="aumentatexto" href="../../../index.php">
                     <!--<img alt="Piraponga" src="../../../images/logo_Piraponga.png" width="80" height="40">-->
                    Piraponga</a>
                </div>

                <div id="navbar" class="navbar-collapse collapse">
                      <ol class="nav navbar-nav" id="topleft">
                          <li class="active"><a href="../../../index.php">Home</a></li>
                          <li><a href="../../../obrasrealizadas.htm">Obras realizadas</a></li>    


                        <!-- submenu -->
                        <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                        Links ?teis<span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li><a href="../../../institucional.htm">Institucional</a></li>
                                <li><a href="../../../trabalheconosco.htm">Trabalhe 
                                conosco</a></li>
                                <li><a href="../../../relacoescomerciais.htm">Rela??es 
                                Comerciais</a></li>
                                <li><a href="http://webmail.Piraponga.srv.br" target="_blank">
                                Webmail</a></li>
                                <li><a href="../../../sitemap/sitemap.html">Sitemap</a></li>
                                <li><a href="../../../contato.htm">Contato</a></li>

                            </ul>
                        </li>
                    </ol>
                      <ol class="nav navbar-nav navbar-right" id="topright">
                          <!--
                            <li><a href="../navbar/">Default</a></li>
                           <li><a href="../navbar-static-top/">Static top</a></li>
                            <li class="active"><a href="./">Fixed top <span class="sr-only">(current)</span></a></li>
                         -->

                         <!-- submenu -->
                         <li class="dropdown">
                         <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                            Produtos e Servi?os<span class="caret"></span></a>                         
                             <ul class="dropdown-menu" role="menu">
                                <li><a href="../../../projeto_de_engenharia.htm">Projeto 
                                de Engenharia</a></li>                            
                                <li><a href="../../../construcao_e_montagem.htm">
                                Constru??o e Montagem</a></li>                            
                                <li><a href="../../../manutencao.htm">Manuten??o</a></li>
                            </ul>    
                         </li>
                         <!-- END submenu -->                        

                          <li><a href="http://www.Piraponga.srv.br"><img src="../../../images/br.jpg" alt="br"></a></li>
                          <li><a href="../../../en/"><img src="../../../images/en.jpg" alt="en"></a></li>
                     </ol>    
                </div> <!-- fecha navbar-->
            </div> <!--fecha menutop-->
            </nav>
        </div>    <!-- fecha header -->
        <div id="main">            

            <div class="container-fluid">
                 <div class="row">
                    <div class="col-sm-3 col-md-2 sidebar" id="fundobranco">                                      
                    <img src="../../../images/002.gif" alt="menu_cima" width="250" height="69">
                        <ul class="nav nav-sidebar" id="primary-nav">
                               <li class="active"><a href="../../../index.php">Home <span class="sr-only">
                            (current)</span></a></li>                            
                            <li><a href="../../../institucional.htm">Institucional</a></li>                        
                            <li class="menuparent"><a href="../../../obrasrealizadas.htm">
                            Obras realizadas</a></li>
                            <li class="menuparent"><a href="../../../relacoescomerciais.htm">
                            Rela??es Comerciais</a></li>
                            <li class="menuparent"><a href="../../../trabalheconosco.htm">
                            Trabalhe conosco</a></li>
                             <li class="menuparent"><a href="../../../contato.htm">Contato</a></li>                    
                          </ul>


                      <img src="../../../images/sbg.gif" alt="menu_baixo" width="250" height="247">

                    </div>   

                    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
                          <h1 class="page-header"><?php echo "$titulo"; ?>
                          <!--Links redes sociais-->
                        <br>
                          <a class="btn btn-social-icon btn-linkedin navbar-right" href="https://www.linkedin.com/company/Piraponga---manuten-es-t-cnicas-ltda" target="_blank">
                        <i class="fa fa-linkedin"></i>
                        </a>                
                        <a class="btn btn-social-icon btn-facebook navbar-right" href="https://www.facebook.com/pages/Piraponga/1633880593511496" target="_blank">
                        <i class="fa fa-facebook"></i>
                        </a>                
                        <a class="btn btn-social-icon btn-google navbar-right" href="https://plus.google.com/+PirapongaSrvBr" target="_blank">
                        <i class="fa fa-google"></i>
                        </a> 

                        </h1>


                         <br>
                         <script>
                        <!--
                        function EnviarNoticia(URL) {
                          var width = 365;
                          var height = 200;
                          var left = 50;
                          var top = 10
                          window.open(URL, 'ema3', 'width='+width+', height='+height+', top='+top+', left='+left+', scrollbars=no, status=no, toolbar=no, location=no, directories=no, menubar=no, resizable=no, fullscreen=no');
                        }
                        -->
                        </script>



        <br>
        <br>
            <?php echo "$subtitulo"; ?>
        <div align="right" style="padding-right: 0.5em">
        <span class="ft1"><a href="#" onclick="TamFonte(1, 'noticia')" class="ft1">A</a></span>&nbsp;
        <span class="ft2"><a href="#" onclick="TamFonte(2, 'noticia')" class="ft2">A</a></span>&nbsp;
        <span class="ft3"><a href="#" onclick="TamFonte(3, 'noticia')" class="ft3">A</a></span>
        </div>
        <div id="noticia" class="ft1 justify">


            <?php         // query SQL
               $strSQL0 = "SELECT foto0 FROM noticias WHERE id='$id'";

               // Executa a query (o recordset $rs0 cont?m o resultado da query)
               $rs0 = mysqli_query($strSQL0);


               // Loop pelo recordset $rs0
            while($row0 = mysqli_fetch_array($rs0)) {


                if ($row0['foto0'] != '') {

                      echo "<div class='row placeholders'><div class='col-xs-12 col-sm-12 placeholder center'><a href=" . $foto0 . " data-lightbox=" . $subtitulo . " data-title=" . "Foto por: " . $fonte_foto . " ><img src=" . $foto0 . " width='400' height='400' class='img-responsive'></a></div></div>";
                }

            }    


            ?>

            <br>
            <?php print (nl2br(htmlentities($texto))); ?>
            <br>
            <br>
            <div class="row placeholders">


             <?php         // query SQL
                $strSQL = "SELECT foto1 FROM noticias WHERE id='$id'";

                // Executa a query (o recordset $rs cont?m o resultado da query)
                $rs = mysqli_query($conn, $strSQL);


                // Loop pelo recordset $rs
                while($row = mysqli_fetch_array($rs)) {


                    if ($row['foto1'] != '') {

                         echo "<div class='col-xs-12 col-sm-3 placeholder'><a href=" . $foto1 . " data-lightbox=" . $subtitulo . " data-title=" . "Foto por: " . $fonte_foto . " ><img src=" . $foto1 . " class='img-responsive'></a></div>";
                    }

                }    


                ?>



            <?php         // query SQL
               $strSQL2 = "SELECT foto2 FROM noticias WHERE id='$id'";

               // Executa a query (o recordset $rs cont?m o resultado da query)
               $rs2 = mysqli_query($conn, $strSQL2);


               // Loop pelo recordset $rs2
            while($row2 = mysqli_fetch_array($rs2)) {


                if ($row2['foto2'] != '') {

                      echo "<div class='col-xs-12 col-sm-3 placeholder'><a href=" . $foto2 . " data-lightbox=" . $subtitulo . " data-title=" . "Foto por: " . $fonte_foto . " ><img src=" . $foto2 . " class='img-responsive'></a></div>";
                }

            }    


            ?>




            <?php         // query SQL
               $strSQL3 = "SELECT foto3 FROM noticias WHERE id='$id'";

               // Executa a query (o recordset $rs3 cont?m o resultado da query)
               $rs3 = mysqli_query($conn, $strSQL3);


               // Loop pelo recordset $rs3
            while($row3 = mysqli_fetch_array($rs3)) {


                if ($row3['foto3'] != '') {

                      echo "<div class='col-xs-12 col-sm-3 placeholder'><a href=" . $foto3 . " data-lightbox=" . $subtitulo . " data-title=" . "Foto por: " . $fonte_foto . " ><img src=" . $foto3 . "  class='img-responsive'></a></div>";
                }

            }    


            ?>

            <?php         // query SQL
               $strSQL4 = "SELECT foto4 FROM noticias WHERE id='$id'";

               // Executa a query (o recordset $rs4 cont?m o resultado da query)
               $rs4 = mysqli_query($conn, $strSQL4);


               // Loop pelo recordset $rs4
            while($row4 = mysqli_fetch_array($rs4)) {


                if ($row4['foto4'] != '') {

                      echo "<div class='col-xs-12 col-sm-3 placeholder'><a href=" . $foto4 . " data-lightbox=" . $subtitulo . " data-title=" . "Foto por: " . $fonte_foto . " ><img src=" . $foto4 . "  class='img-responsive'></a></div>";
                }

            }    


            ?>



            </div>

              <div class="cat_data_hora" style="padding-top:1em; text-align:right;">Not?cia cadastrada em: <?php echo "$data - $hora"; ?> FONTE: <?php echo $fonte; ?></div>
                          <br>
                          <br>
                           <div align="center" class="cat_data_hora" style="text-align:center"><br>
                            <a href="imprimir.php?noticia=<?php echo $id; ?>" target="_blank"><img src="img/imprimir.gif" width="14" height="15" border="0" alt="vers?o para impress?o"></a> |
                            <a href="javascript:EnviarNoticia('enviar.php?noticia=<?php echo $id ?>')"><img src="img/enviar_not.png" width="16" height="16" border="0" alt="enviar not?cia por email"></a> |        
              <?php echo "<a href='whatsapp://send?text=Ol?, veja s? essa not?cia no site da Piraponga com t?tulo: " . $titulo . ", segue link: http://www.Piraponga.srv.br/painel/noticias/exibir.php?noticia=" . $id . "'><img src='../../../images/whatsapp.png'></a>"; ?>
              <?php echo "<a href='http://www.facebook.com/share.php?u=http://www.Piraponga.srv.br/painel/noticias/exibir.php?noticia=" . $id . "'><img src='../../../images/facebook.png'></a>"; ?>
              <?php echo "<a href='https://plus.google.com/share?url=http://www.Piraponga.srv.br/painel/noticias/exibir.php?noticia=" . $id . "'><img src='../../../images/google.png'></a>"; ?>
              <?php echo "<a href='http://twitter.com/share?url=http://www.Piraponga.srv.br/painel/noticias/exibir.php?noticia=" . $id . "&text=" . $titulo . "'><img src='../../../images/twitter.png'></a>"; ?>
              <?php echo "<a href='https://www.linkedin.com/shareArticle?mini=true&url=http%3A//www.Piraponga.srv.br/painel/noticias/exibir.php?noticia=" . $id . "&title=" . $titulo . "&summary=&source='><img src='../../../images/linkedin.png'></a>"; ?>
                            <a href="javascript:window.history.go(-1)" class="cat_data_hora">Voltar</a>
                        </div>

                            <br>
                              <br>
                          </div>
                      </div>
                  </div>
              </div>
          </div> <!-- fecha main -->
    </div>    <!-- fecha wrap -->
<?php

            break;
        }
    }
}

?>                                 
            <div class="container" id="footer">
                <img class="maxwidth" src="../../../images/footer.png" alt="footer" height="153">                
                <div class="col-xs-6 col-sm-3 placeholder" id="logo_footer">
                    <img src="../../../images/logo_Piraponga.png" alt="logo Piraponga" class="img-responsive">                
                </div>
                <p style="TEXT-ALIGN: center">Rua do Petr?leo &#8211; Lote 1, Quadra J &#8211;  </p>                
            </div>        



    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="../../../js/bootstrap.min.js" type="text/javascript"></script>        
    <script src="../../../js/holder.js" type="text/javascript"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="../../../js/ie10-viewport-bug-workaround.js" type="text/javascript"></script>
</body>

</html>
  • Strange, is working normally your code, the only problem that is appearing here is the $news variable that does not exist. Is there any more detail?

  • I also found this variable strange, but it worked in PHP 5.3. I did a test, when placing a div after the break, this div is displayed on the page. if I move this break to just after the case, the full layout of the page is displayed, and the last registered news is displayed(7), regardless if I click on the news 1, 2, 3, etc...and the news photos in this case do not load (the code that calls them is inside html):

  • Have you tried searching for this variable in another file? Do you have a file that calls this file?

  • How does the script behave when you remove the switch? You have also checked function closures?

  • in this.php display file it only calls the.php connection whose code I put in my question;

  • Excuse me, I think I asked the wrong way. It was to know if there is another file that calls the file display.php.

  • yes, it’s called in the exibe_news.php: echo . $data . " - " . $hour . ": <img src='dashboard/news/img/maq.gif' width='14' height='14' title='NEWS WITH IMAGE' alt='NEWS WITH IMAGE'><a href='dashboard/news/display.php? noticia=" . $id . " '> " . $title . " - " . $subtitle . " </a><br></div><br>";

  • I added the html code to see if it helps with something...but it’s kind of extensive. note the <div class="container" id="footer">, only it is displayed when I click on some news, I believe that pq is after break.

  • On this line you call "echo $id" but do not include ; at the end <a href="javascript:Enviar noticia('send.php? noticia=<? php echo $id ?>')">

  • true! but it made no difference when fixing;

  • The line $rs0 = mysqli_query($strSQL0); is without the connection variable, after this fix no longer presents any errors, now just check that your database is not with an Injection sql

Show 6 more comments

1 answer

0

I managed to solve it, in php 5.3 I don’t need to declare the news variable. It was enough to declare

$noticia = $_GET['noticia'];

Which worked, the script "picks up" the id declared in the url

http://www.piraponga.srv.br/painel/noticias/exibir.php?noticia=7

O.b.r.i.g.a.d.o.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.