# PHP/MySQL Search Question - Big One!



## Akumos (Apr 30, 2012)

Hi All

This is quite a big question so I understand if no one wants to answer lol

account for site
Username: test
Password: pass

I have this 'Scout for Target' form here - I want to be able to make a search based on the input from the user. But if they leave a field blank, it ignores it in the search...

will this mean, lots of if statements or is there an easy way to do this?

thanks for reading


----------



## Ross211 (May 1, 2012)

You won't need lots of if statements...

```
<?php
if (isset($_POST['playerid'])) {
	// sanitize every post variable and put it in an array called clean
	foreach(array_keys($_POST) as $key) { 
	  $clean[$key] = mysqli_real_escape_string($dbc, $_POST[$key]);
	} 
	$sql = "SELECT * 
	FROM `TableHere` 
	WHERE playerid = '{$clean['playerid']}';";
	$result = mysqli_query($dbc, $sql);
}
?>
```

If you are searching through multiple tables I can help you with joins.  If you aren't using prepared statements its a good idea to use that foreach loop above to sanitize every one of your POST or GET variables on form submit.

From the looks of your search page you are submitting the form using the POST method and then calling a header to send the user to searchplayer.php - I noticed no parameters are being put in the searchplayer.php script though.

Are you intending to do something like this below ?

This code below would be in the header of search.php - 

```
<?php
if (isset($_POST['playerid'])) {
	header('location: /searchplayer.php?playerid='.urlencode($_POST['playerid']));
}
?>
```

And then this code would be in the header of searchplayer.php - 

```
<?php
if (isset($_GET['playerid'])) {
	// sanitize every get variable and put it in an array called clean
	foreach(array_keys($_GET) as $key) { 
	  $clean[$key] = mysqli_real_escape_string($dbc, $_GET[$key]);
	} 
	$sql = "SELECT * 
	FROM `TableHere` 
	WHERE playerid = '{$clean['playerid']}';";
	$result = mysqli_query($dbc, $sql);
} else {
	header('location: /search.php?playerid=empty');
}
?>
```

Please let me know if this helps.


----------



## Akumos (May 15, 2012)

Thanks for this - helped alot!


----------



## Ross211 (May 15, 2012)

Hey you're welcome Akumos, glad I could help.  

Can I ask what the PeaceKeeper Alliance is?  Is it a game that runs through the web browser?

About 2 weeks ago I logged in using your provided test login and I didn't quite understand what it is.  I was able to look at the code on your web forms and understand what you were wanting to accomplish though.  

On a side note I just graduated college and I'm on the hunt for a position as a web developer.  I initially got into PHP and JavaScript to learn how to steal cookies and perform XSS attacks - coding against security exploits is one of my strong points ;~)


----------

