Foros del Web » Programando para Internet » PHP »

Problema con script de búsqueda

Estas en el tema de Problema con script de búsqueda en el foro de PHP en Foros del Web. Hola, tengo un problema con un script de búsqueda. Estoy siguiendo un sencillo ejemplo que te permite buscar y enlistar una serie de chistes, almacenados ...
  #1 (permalink)  
Antiguo 17/04/2005, 10:02
 
Fecha de Ingreso: abril-2005
Mensajes: 50
Antigüedad: 19 años
Puntos: 0
Problema con script de búsqueda

Hola, tengo un problema con un script de búsqueda. Estoy siguiendo un sencillo ejemplo que te permite buscar y enlistar una serie de chistes, almacenados en una base de datos, según autor, categoría y/o palabra.

Mi problema es que cuando la búsqueda no encuentra ningún registro en la base de datos, en vez de que aparezca un mensaje diciendo, por ejemplo: NO se encontraron resultados!....; el resultado se queda en blanco.

Al quedarse en blanco es de alguna manera obvio que no se encontraron resultados, sin embargo es más amigable y presentable que aparezca un mensaje que indique esto.

¿Cómo puedo modificar el script para que muestre algún mensaje, si no se han encontrado registros en la Base de Datos?

Saludos y gracias,

A continuación pongo los scripts:

Página de búsqueda ---------------------------------------------------

Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Joke CMS: Manage Jokes</title>
<meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Manage Jokes</h1>
<p><a href="newjoke.php">Create New Joke</a></p>
<?php
  
$dbcnx 
= @mysql_connect('localhost''root''psswd');
if (!
$dbcnx) {
  exit(
'<p>Unable to connect to the ' .
      
'database server at this time.</p>');
}

if (!@
mysql_select_db('ijdb')) {
  exit(
'<p>Unable to locate the joke ' .
      
'database at this time.</p>');
}

$authors = @mysql_query('SELECT id, name FROM author');
if (!
$authors) {
  exit(
'<p>Unable to obtain author list from the database.</p>');
}

$cats = @mysql_query('SELECT id, name FROM category');
if (!
$cats) {
  exit(
'<p>Unable to obtain category list from the database.</p>');
}
?>

<form action="jokelist.php" method="post">
<p>View jokes satisfying the following criteria:</p>
<label>By author:
<select name="aid" size="1">
  <option selected value="">Any Author</option>
<?php
while ($author mysql_fetch_array($authors)) {
  
$aid $author['id'];
  
$aname htmlspecialchars($author['name']);
  echo 
"<option value='$aid'>$aname</option>\n"
}
?>
</select></label><br />
<label>By category:
<select name="cid" size="1">
  <option selected value="">Any Category</option>
<?php
while ($cat mysql_fetch_array($cats)) {
  
$cid $cat['id'];
  
$cname htmlspecialchars($cat['name']);
  echo 
"<option value='$cid'>$cname</option>\n"
}
?>
</select></label><br />
<label>Containing text: <input type="text" name="searchtext" /></label><br />
<input type="submit" value="Search" />
</form>

<p><a href="index.html">Return to front page</a></p>
</body>
</html>
Script que procesa la búsqueda y página de resultados ------------------

Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Joke CMS: Manage Jokes</title>
<meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Manage Jokes</h1>
<?php

$dbcnx 
= @mysql_connect('localhost''root''psswd');
if (!
$dbcnx) {
  exit(
'<p>Unable to connect to the ' .
      
'database server at this time.</p>');
}

if (!@
mysql_select_db('ijdb')) {
  exit(
'<p>Unable to locate the joke ' .
      
'database at this time.</p>');
}

// The basic SELECT statement
$select 'SELECT DISTINCT id, joketext';
$from   ' FROM joke';
$where  ' WHERE 1=1';

$aid $_POST['aid'];
if (
$aid != '') { // An author is selected
  
$where .= " AND authorid='$aid'";
}

$cid $_POST['cid'];
if (
$cid != '') { // A category is selected
  
$from  .= ', jokecategory';
  
$where .= " AND id=jokeid AND categoryid='$cid'";
}

$searchtext $_POST['searchtext'];
if (
$searchtext != '') { // Some search text was specified
  
$where .= " AND joketext LIKE '%$searchtext%'";
}
?>

<table>
<tr><th>Joke Text</th><th>Options</th></tr>

<?php
$jokes 
= @mysql_query($select $from $where);
if (!
$jokes) {
  echo 
'</table>';
  exit(
'<p>Error retrieving jokes from database!<br />'.
      
'Error: ' mysql_error() . '</p>');
}

while (
$joke mysql_fetch_array($jokes)) {
  echo 
"<tr valign='top'>\n";
  
$id $joke['id'];
  
$joketext htmlspecialchars($joke['joketext']);
  echo 
"<td>$joketext</td>\n";
  echo 
"<td><a href='editjoke.php?id=$id'>Edit</a> | " .
      
"<a href='deletejoke.php?id=$id'>Delete</a></td>\n";
  echo 
"</tr>\n";
}
?>

</table>

<p><a href="jokes.php">New search</a></p>
</body>
</html>
  #2 (permalink)  
Antiguo 17/04/2005, 10:32
 
Fecha de Ingreso: enero-2004
Ubicación: Salto
Mensajes: 484
Antigüedad: 20 años, 3 meses
Puntos: 2
podrías usar un mysql_num_rows si el resultado es 0 imprimes lo q quieras, si es distinto de 0, le mandas el while, algo mas o menos así
$total_datos = mysql_num_rows($joke);
if($total_datos == 0){
echo "No se encontraron datos";
}else{
while bla bla
}
__________________
Dios dira que esto no es justo, pero lo sera...
  #3 (permalink)  
Antiguo 17/04/2005, 10:56
 
Fecha de Ingreso: abril-2005
Mensajes: 50
Antigüedad: 19 años
Puntos: 0
Listo... ;0)

La función mysql_num_rows era lo que me hacía falta, había intentado usar la combinación de if and else pero sin la función y no servía.

Tu solución funciona muy bien,

Gracias

Última edición por raml; 17/04/2005 a las 11:07
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:46.