0

I'm trying to create a search box with classes, i always use a specific code for this, whithout using classes.

But now, im learning how to use classes, and i need to transfer my old code, to a single class, i tried this function:

function verGaleria() {
    $sql = "SELECT * FROM `cds`";
    if(($rs=$this->bd->executarSQL($sql))){
      if(isset($_GET['buscar'])){
        $sql = mysql_query("SELECT * FROM `cds` where name like '%".$_GET['buscar']."%'");
      }

      while ($row = mysql_fetch_array($rs)) {                   
              $imagem = $row['imagem'];
              $ID = $row['ID'];
              $artista = $row['artista'];
              $preco = $row['preco'];
              $titulo = $row['titulo'];

        echo '      
                <style>
                .teste{
                text-align:center; display: inline-block; width:300px; margin: 0 0 40px 30px;   float:left; color:white;
                }
                </style>
          <div class="teste">
                  <h1>'.$titulo.'</h1>
                      <h2><img class="cd" src="CDs/'.$imagem.'" width="102" height="126" alt="'.$artista.'"/></h2>
                        <h3>'.$preco.'€</h3>
          </div>
            ';
    }   
  } else {
    return false;
    }
}

My from code:

<form method="GET" name="buscar" >
 <label><a class="utilizador">Procurar</a>
 <br />
   <input type="text" name="buscar" id="prc" placeholder="Ex: Rock"/></label>
    <input type="submit" class="submitprc" value="Pesquisar" />
</form>
span
  • 5,405
  • 9
  • 57
  • 115

1 Answers1

1

You are executing the initial SQL query $sql = "SELECT * FROMcds"; which fetches all the products and storing all results in $rs like so $rs=$this->bd->executarSQL($sql)

Then you check if search query is present isset($_GET['buscar']) and if it is present then you form your new sql statement $sql = mysql_query("SELECT * FROMcdswhere name like '%".$_GET['buscar']."%'"); but you never execute it.

Then you use $rs to show the results..

while ($row = mysql_fetch_array($rs)) {
    $imagem = $row['imagem'];
    $ID = $row['ID'];
    $artista = $row['artista'];
    $preco = $row['preco'];
    $titulo = $row['titulo'];
//code
}

What you should do is something like:

<?php

isset($_GET['buscar']) ?
    $sql = "SELECT * FROM `cds` where name like '%".$_GET['buscar']."%'" :
    $sql = "SELECT * FROM `cds`";

$result = mysql_query("SELECT * FROM `cds` where name like '%".$_GET['buscar']."%'", $conn); // pass in your connection object

 if(! $result )
 {
    die('Could not get data: ' . mysql_error());
 }

 while ($row = mysql_fetch_array($result)) {
    $imagem = $row['imagem'];
    $ID = $row['ID'];
    $artista = $row['artista'];
    $preco = $row['preco'];
    $titulo = $row['titulo'];

   //code
}
Lucky Soni
  • 6,811
  • 3
  • 38
  • 57