Jump to content

Problem with WHILE loop


kpetsche20

Recommended Posts

I"m trying to make a search function.  But whenever the statement comes back false

 

I get this mesage is just repeats.

 

no record foundno record foundno record foundno record foundno record foundno record foundno record foundno record foundno record foundno record found

 

<table width="550" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
   <td width="522"><p>Search </p>

<?php
if(isset($_POST['submit']))
{
$sql = "SELECT * FROM tblpeople";
$run = mysql_query($sql);

while($data = mysql_fetch_array($run))
{

if($_POST['search'] == $data['indlastname'])
{
echo $data['indlastname'];
}
else { echo "no record found"; }
}


}




else {
?>
   
<form action="index.php?p=search" method="POST">



<input name="search" type="text" />
<input type="submit" name="submit" value="submit" />
</form>        <?  }  ?></td>
</tr>
</table>

Link to comment
https://forums.phpfreaks.com/topic/113391-problem-with-while-loop/
Share on other sites

Hey,

 

Try this for ur php code

<?php
if(!isset($_POST['submit']))
{die();}

$sql = "SELECT * FROM tblpeople";
$run = mysql_query($sql);

while($data = mysql_fetch_array($run))
{
if($_POST['search'] == $data['indlastname'])
{
	echo $data['indlastname'];
}
else { 
	echo "no record found"; 
}
}
?>

Hi , thats because for every row its doing the same check. So if it doesnt match search you told it to echo that message.

 

Its not an efficient way of doing it, as the result returned from the database query could be huge.

 

You should include the search string into the sql query with a where clause and check the sql result once.

 

Hope that helps.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.