我正在尝试使用类创建一个搜索框,我总是使用特定的代码,而不使用类。
但是现在,我正在学习如何使用类,我需要将我的旧代码转移到单个类,我尝试了这个函数:
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;
}
}
我的代码:
<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>
答案 0 :(得分:1)
您正在执行初始SQL查询$sql = "SELECT * FROM
cds ";
,它会抓取所有产品并将所有结果存储在$rs
中,如$rs=$this->bd->executarSQL($sql)
然后检查搜索查询是否存在isset($_GET['buscar'])
,如果它存在,那么你形成新的sql语句$sql = mysql_query("SELECT * FROM
cds where name like '%".$_GET['buscar']."%'");
,但你永远不会执行它。
然后使用$rs
显示结果..
while ($row = mysql_fetch_array($rs)) {
$imagem = $row['imagem'];
$ID = $row['ID'];
$artista = $row['artista'];
$preco = $row['preco'];
$titulo = $row['titulo'];
//code
}
你应该做的是:
<?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
}