Page 1 of 1

Message for empty array (search)

Posted: Tue Nov 23, 2010 3:33 pm
by phpnovice1
Hello

I have a HTML page with a short form which allows the user search my mySQL database based on the available criteria. The script works ok and returns the relevant information when the input info matches the database data. However, when there is no matching info the result is a blank page/table.

My question is how do i get a message to show when an empty array is returned? I've messed about with the code and i can get a ' sorry your search returned no results' message, but then it returns the same message when the info matches too. Here is my code php code......

<?php

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* function block of code that you call that takes
* one or more value (arguments) and returns a result
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
function sql_to_array($result)
{
$results = array();

while($row = mysql_fetch_assoc($result))
{
array_push($results, $row);
}

return $results;
}

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* main body code
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
// open the connection
$conn = mysql_connect("localhost", "total", "nobody");

// pick the database to use
mysql_select_db("learn",$conn);

// As all the names in the database are lowercase, the
// query string is converted to lowercase
$experience = strtolower(


// It is also ran through mysql_real_escape_string
// so that the program is not vonerable to SQL
// injection

mysql_real_escape_string(

// Take the result out of the POST array, which comes
// from the HTML form
$_POST['Experience']));

$level = strtolower(
mysql_real_escape_string($_POST['Level']));

$location = strtolower(
mysql_real_escape_string($_POST['Location']));



// create the SQL statement
$sql = "
SELECT * FROM `player`
WHERE `Experience` = '$experience' AND `Level` = '$level' AND `Location` = '$location'" ;

// execute the SQL statement
if ($result = mysql_query($sql, $conn))
{
// Convert the mysql resource into an array
// using the function defined above
$results = sql_to_array($result);

// Load a template (view) file to display the results in a table
include "template.php";
}
elseif ($result = array())
{

echo "<strong>Sorry, your search returned no results</strong>";
}

?>
</body>
</html>

I would really appreciate your help

Many thanks

Re: Message for empty array (search)

Posted: Wed Nov 24, 2010 1:20 am
by requinix

Code: Select all

elseif ($result = array()) 
1. = is for assignment, == is for comparison.
2. mysql_query does not return an empty array if it fails.
3. "Failure" does not include "no results". It means there was a problem attempting to execute the query.
4. To see if there weren't any results, use a function like mysql_num_rows or check if the sql_to_array returned an empty array.