I have a simple form which echoes data from db. when name typed. It works fine when name is typed and submit pressed.
But I see that even when no name is selected or, when existing results on screen, pressing submit brings up ALL names from table not just row containing $name.
How can I stop this happening and have only row with $name displayed?
The code I am using is (have tried with $_POST with same result)

<?php
if (isset($_GET['name'])) $name = $_GET ['name'];
else $name = "(Not entered)";
echo <<<_END
<html>
	<head>
		<title>Allaunch</title>
	</head>
	<body>		
	<form method="get" action="allaunch.php">
		Enter Ship Name
		<input type="text" name="name" size="25" maxlength ="35"/>
		<input type="image" name="submit"/>
	</form>
	<font color="blue" size="4px"/>You searched for: $name<br/>
	</body>
	</html>
_END;
require_once 'login.php';
$db_server = mysql_connect('localhost', 'root','');

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());      mysql_select_db('shipdb')
	or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM allnames WHERE name1 LIKE '$name%' OR name2 LIKE '$name%' OR name3 LIKE '$name%' OR name4 LIKE '$name%' OR name5 LIKE '$name%'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows=mysql_num_rows($result);
if(mysql_num_rows($result)==0)
{
echo "No data found for your request. Try a different query.";
exit;}
for ($j=0; $j < $rows ; ++$j)
{
$row =mysql_fetch_row($result);

	$subquery = "SELECT * FROM launch WHERE ID = '$row[0]'";
	$subresult = mysql_query($subquery);
	if (!$subresult) die ("Database access failed: " . mysql_error());
	$subrow = mysql_fetch_row($subresult);
// there follow tables all of which are excuted correctly.
Member Avatar for diafol

echo out the query to see what it gives you. If any are blank, e.g.

name1 LIKE '%'

You may find that you get all records returned. Just a thought.

I added a few lines I found in another post and this has cured it.
A fluke ? Anyway it is working now.

if($name == "")
{
echo "<p><font color='red' size='4px'>You have not entered a name</font></p>";
exit;
}
else
{
echo "<p><font color='blue' size='4px'>You searched for: $name</font></p>";
}
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.