Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

TrooN

Busca com ou sem acentos PHP + MySQL

Recommended Posts

Eu tenho esse seguinte campo para fazer a pesquisa:

<form class="templatemo-search-form" method="post" role="search" action="busca.php" name="localizar">
  <div class="input-group">
    <button type="submit" class="fa fa-search"></button>
    <input type="text" class="form-control" placeholder="Localizar Aluno" name="localizar" id="localizar">           
  </div>
</form>

 

Esse código retorna para mim em outra página cujo ela busca no banco de dados MySQL os dados de uma tabela, busca pelos nomes de pessoas. Veja o código completo.

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$colname_verusuario = "-1";
if (isset($_SESSION['MM_Username'])) {
  $colname_verusuario = $_SESSION['MM_Username'];
}
mysql_select_db($database_conexao, $conexao);
$query_verusuario = sprintf("SELECT * FROM adm WHERE usuario = %s", GetSQLValueString($colname_verusuario, "text"));
$verusuario = mysql_query($query_verusuario, $conexao) or die(mysql_error());
$row_verusuario = mysql_fetch_assoc($verusuario);
$totalRows_verusuario = mysql_num_rows($verusuario);

$colname_verbusca = "-1";
if (isset($_POST['localizar'])) {
  $colname_verbusca = $_POST['localizar'];
}
mysql_select_db($database_conexao, $conexao);
$query_verbusca = sprintf("SELECT * FROM alunos WHERE nome LIKE _utf8 %s COLLATE utf8_general_ci ORDER BY nome ASC", GetSQLValueString("%" . $colname_verbusca . "%", "text"));
$verbusca = mysql_query($query_verbusca, $conexao) or die(mysql_error());
$row_verbusca = mysql_fetch_assoc($verbusca);
$totalRows_verbusca = mysql_num_rows($verbusca);
?>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <title>Buscando <?php echo $_POST['localizar']; ?> | People Araxá - Painel Administrativo</title>
    <meta name="description" content="">
    <meta name="author" content="ArtPublicidade">
    <link rel="shortcut icon" href="/img/icon.ico">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,700' rel='stylesheet' type='text/css'>
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/templatemo-style.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="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <!--[endif]-->

  </head>
  <body>  
    <!-- Left column -->
    <div class="templatemo-flex-row">
      <div class="templatemo-sidebar">
        <header class="templatemo-site-header">
          <img src="images/logo_claro.png" class="col-md-12 col-sm-12 col-xs-12" />
        </header>
        <div style="clear: both;"></div>
        <div class="profile-photo-container">
          <img src="images/adm/<?php if($row_verusuario['foto'] == "") { echo "avatar.png"; } else { echo "".$row_verusuario['foto'].""; } ?>" alt="Profile Photo" class="img-responsive">
          <div class="profile-photo-overlay"></div>
        </div>
        <div class="profile-photo-container">
          <div style="clear: both;"></div>
          <div style="color: #ffffff; font-size: 1.5em; text-align: center; padding-top: 0.5em;"><?php echo $row_verusuario['nome']; ?></div>
        </div>
        <!-- Search box -->
        <form class="templatemo-search-form" method="post" role="search" action="busca.php" name="localizar">
          <div class="input-group">
              <button type="submit" class="fa fa-search"></button>
              <input type="text" class="form-control" placeholder="Localizar Aluno" name="localizar" id="localizar">           
          </div>
        </form>
        <div class="mobile-menu-icon">
            <i class="fa fa-bars"></i>
        </div>
        <nav class="templatemo-left-nav">
          <ul>
            <li><a href="restrito.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "restrito") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-home fa-fw"></i></div><div style="display: table-cell;">Início</div></div></a></li>
            <li><a href="editar_dados.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "editar_dados") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-pencil fa-fw"></i></div><div style="display: table-cell;">Editar Dados Pessoais</div></div></a></li>
            <li><a href="enviar_recados_turmas.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "enviar_recados_turmas") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-envelope fa-fw"></i></div><div style="display: table-cell;">Enviar Recados para Turmas</div></div></a></li>
            <li><a href="enviar_recados_professores.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "enviar_recados_professores") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-envelope fa-fw"></i></div><div style="display: table-cell;">Enviar Recados para Professores</div></div></a></li>
            <li><a href="enviar_materiais.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "enviar_materiais") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-upload fa-fw"></i></div><div style="display: table-cell;">Enviar Materiais para Download</div></div></a></li>
            <li><a href="cadastrar_livros.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "cadastrar_livros") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-book fa-fw"></i></div><div style="display: table-cell;">Cadastrar Livros</div></div></a></li>
            <li><a href="cadastrar_videos.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "cadastrar_videos") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-video-camera fa-fw"></i></div><div style="display: table-cell;">Cadastrar Vídeos</div></div></a></li>
            <li><a href="cadastrar_discussao.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "cadastrar_discussao") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-microphone fa-fw"></i></div><div style="display: table-cell;">Cadastrar Discussão</div></div></a></li>
            <li><a href="administrar_comentarios.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "administrar_comentarios") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-comments fa-fw"></i></div><div style="display: table-cell;">Administrar Comentários das Discussões</div></div></a></li>
            <li><a href="fotos_alunos.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "fotos_alunos") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-picture-o fa-fw"></i></div><div style="display: table-cell;">Ver Fotos Alunos</div></div></a></li>
            <li><a href="cadastrar_alunos.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "cadastrar_alunos") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-user-plus fa-fw"></i></div><div style="display: table-cell;">Cadastrar Alunos</div></div></a></li>
            <li><a href="ver_curriculos.png" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "ver_curriculos") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-file-text-o fa-fw"></i></div><div style="display: table-cell;">Ver Currículos</div></div></a></li>
            <li><a href="notas.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "notas") { echo "class='active'"; } else {} ?>><div style="display: table;"><div style="display: table-cell; vertical-align: middle;"><i class="fa fa-pencil-square-o fa-fw"></i></div><div style="display: table-cell;">Administrar Notas Alunos</div></div></a></li>
            <?php if($row_verusuario['cargo'] == "administrador") { ?>
			<li><a href="administrar-usuarios.php" <?php if(basename($_SERVER['PHP_SELF'],'.php') == "administrar-usuarios" or basename($_SERVER['PHP_SELF'],'.php') == "editar_user") { echo "class='active'"; } else {} ?>><i class="fa fa-users fa-fw"></i>Administrar Usuários</a></li>
            <?php } else { } ?>
            <li><a href="<?php echo $logoutAction ?>"><i class="fa fa-sign-out fa-fw"></i>Sair</a></li>
          </ul>  
        </nav>
      </div>
      <!-- Main content --> 
      <div class="templatemo-content col-1 light-gray-bg">
        <div class="templatemo-content-container">
          <div class="templatemo-content-widget no-padding">
            <div class="panel panel-default table-responsive">
              <div class="col-md-12 col-sm-12 col-xs-12">
              <?php do { ?>
                <?php echo $row_verbusca['nome']; ?><br>
<?php } while ($row_verbusca = mysql_fetch_assoc($verbusca)); ?>
<input type="text" name="nome" class="col-md-12 col-sm-12 col-xs-12" placeholder="Nome" /></div>
              </div></div>
          <footer class="text-right">
            <p>Copyright © <?php echo date('Y'); ?> People Araxá | Desenvolvido por <a href="http://www.artpublicidade.com.br" target="_parent">ArtPublicidade</a></p>
          </footer>         
        </div>
      </div>
    </div>
    
    <!-- JS -->
    <script src="js/jquery-1.11.2.min.js"></script>      <!-- jQuery -->
    <script src="js/jquery-migrate-1.2.1.min.js"></script> <!--  jQuery Migrate Plugin -->
    <script src="https://www.google.com/jsapi"></script> <!-- Google Chart -->
    <script>
      /* Google Chart 
      -------------------------------------------------------------------*/
      // Load the Visualization API and the piechart package.
      google.load('visualization', '1.0', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawChart); 
      
      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

          // Create the data table.
          var data = new google.visualization.DataTable();
          data.addColumn('string', 'Topping');
          data.addColumn('number', 'Slices');
          data.addRows([
            ['Mushrooms', 3],
            ['Onions', 1],
            ['Olives', 1],
            ['Zucchini', 1],
            ['Pepperoni', 2]
          ]);

          // Set chart options
          var options = {'title':'How Much Pizza I Ate Last Night'};

          // Instantiate and draw our chart, passing in some options.
          var pieChart = new google.visualization.PieChart(document.getElementById('pie_chart_div'));
          pieChart.draw(data, options);

          var barChart = new google.visualization.BarChart(document.getElementById('bar_chart_div'));
          barChart.draw(data, options);
      }

      $(document).ready(function(){
        if($.browser.mozilla) {
          //refresh page on browser resize
          // http://www.sitepoint.com/jquery-refresh-page-browser-resize/
          $(window).bind('resize', function(e)
          {
            if (window.RT) clearTimeout(window.RT);
            window.RT = setTimeout(function()
            {
              this.location.reload(false); /* false to get page from cache */
            }, 200);
          });      
        } else {
          $(window).resize(function(){
            drawChart();
          });  
        }   
      });
      
    </script>
    <script type="text/javascript" src="js/templatemo-script.js"></script>      <!-- Templatemo Script -->
  </body>
</html>

A questão é a seguinte, não consegui fazer com que quando eu pesquisar aparece tanto as palavras que cadastrei com acento e as que estão sem acento ao mesmo tempo.

Estou usando utf8 no SELECT do banco, mas com isso ele está retornando para mim somente os que não tem acentos mesmo eu procurando com acento ou não. Se eu tirar o UTF8 do SELECT ele procura separado, se digitar com acento ele aparece só os que tem acento, se digitar sem acento só encontra os que não tem acento.

 

Como faço para resolver esse problema, quero poder encontrar os dois resultados mas pode procurar de qualquer uma das duas maneiras.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.