I'm looking for a way to get lots of user inputs, concatenate them into one sql query, and return the results from my database. I have tried a few different techniques so far including putting all the variables into an array then using implode() but I couldn't get it to work. For simplicity sake I have decided to just go with a couple of if statements to check if each variable has a value in it or not. If it does then it should add some sql. My error message from this is as follows:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'AND type = AND (city LIKE '%%') OR (addressLineOne LIKE
'%%') OR (`addres' at line 1
It appears that $type is not being picked up even though I gave it a input during the test. I have not given any other inputs values besides $type and $bedroom.
Any help and improvement on the code would be greatly appreciated. I'm new to PHP and SQL so sorry if it's something stupid, but I have tried to fix this for ages.
HTML
<form action="searchresults.php" method="get">
<fieldset>
<legend><h3>Search</h3></legend>
<p>Please enter criteria for your search.</p>
<label for="location">Location</label>
<input type="text" name="location" />
<select name="type">
<option value="Studio Flat" selected>Studio Flat</option>
<option value="Flat">Flat</option>
<option value="Detached">Detached</option>
<option value="Semi-detached">Semi-detached</option>
<option value="Terraced">Terraced</option>
<option value="Bungalow">Bungalow</option>
</select>
<label for="bedroom">Bedrooms</label>
<select name="bedroom">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<label for="min">Min Price</label>
<input type="number" name="min" />
<label for="max">Max Price</label>
<input type="number" name="max" />
<br />
<input type="submit" value="Search" />
</fieldset>
</form>
PHP
<?php
session_start();
include './auth.php'; // connection to db
$location = trim($_POST['location']);
$location = strip_tags($location);
$location = htmlspecialchars($location);
$bedroom = trim($_POST['bedroom']);
$bedroom = strip_tags($bedroom);
$bedroom = htmlspecialchars($bedroom);
$type = trim($_POST['type']);
$type = strip_tags($type);
$type = htmlspecialchars($type);
$max = trim($_POST['max']);
$max = strip_tags($max);
$max = htmlspecialchars($max);
$min = trim($_POST['min']);
$min = strip_tags($min);
$min = htmlspecialchars($min);
// build query
$query = "SELECT * FROM Listings WHERE `bedroom` = ".$bedroom." AND `type` = ".$type."";
if(isset($location)){
$query .= " AND (`city` LIKE '%".$location."%') OR (`addressLineOne` LIKE '%".$location."%') OR (`addressLineTwo` LIKE '%".$location."%') OR (`county` LIKE '%".$location."%')";
}
if(isset($max)){
$query .= " AND (`price` <= '%".$price."%')";
}
if(isset($min)){
$query .= " AND (`price` >= '%".$price."%')";
}
$query .= "ORDER BY price;";
// send query to database and return error if it fails
$input = mysqli_query($connect, $query) or die(mysqli_error($connect));
// output results
if(mysqli_num_rows($input)>0){ // if one or more results returned do this code
while($result = mysqli_fetch_array($input)){ // puts data in array then loops the following code
echo "<p><h3>".$result['addressLineOne']." ".$result['addressLineTwo']."
".$result['location']."</h3><h4>£".$result['price']."</h4>".$result['information']."</p><br /><hr />";
}
}else{ // no results then print the following
echo "Sorry, we couldn't find any results.
Please refine your search and try again.";
}
echo $query;
// close the connection
mysqli_close($connect)
?>
I know you're currently using mysqli, but PDO makes building dynamic queries much easier, so I strongly suggest you switch to it, if you're not very far along on this project.
In a mysqli prepared statement, you have to call mysqli_stmt::bind_param(), passing every parameter in the argument list. In contrast, PDO requires no binding, and the parameters are all passed to PDOStatement::execute() in an array. This answer will show you how your code would work with PDO.
<?php
$connection = new \PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$query = "SELECT * FROM Listings WHERE bedroom = :bed AND type = :type AND (city LIKE :loc OR addressLineOne LIKE :loc OR addressLineTwo LIKE :loc OR county LIKE :loc)";
$parameters = [
":bed" => $_POST["bedroom"],
":type" => $_POST["type"],
":loc" => "%$_POST[location]%",
];
if(!empty($_POST["max"])) {
$query .= " AND price <= :max";
$parameters[":max"] = $_POST["max"];
}
if (!empty($_POST["min"])) {
$query .= " AND price >= :min";
$parameters[":min"] = $_POST["min"];
}
$query .= " ORDER BY price";
$stmt = $connection->prepare($query);
$stmt->execute($parameters);
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results)) { // no results then print the following
echo "Sorry, we couldn't find any results. Please refine your search and try again.";
}
foreach ($results as $result) {
//escape for HTML output
$result = array_map("htmlspecialchars", $result);
echo <<< HTML
<p>
<h3>$result[addressLineOne] $result[addressLineTwo] $result[location]</h3>
<h4>£$result[price]</h4>
$result[information]
</p>
<br />
<hr />
HTML;
}
I've also simplified your HTML output by using a heredoc string, but you should really have your HTML and PHP separated.
If this is part of a much bigger existing project, you will likely be sticking with mysqli, in which case I urge you to learn how to use prepared statements; the days of building queries with string concatenation are long behind us!
Using PDO and bound parameters as #miken32 suggests is a possibility, but I advise against it because it has several downsides:
You are currently using mysqli, which also supports bound parameters, so no reason to switch to PDO just to get parameter binding
#miken32's solution uses a named parameter (something only PDO supports) multiple times in the query. This only works when client-side parameter binding is enabled (i.e. PDO::ATTR_EMULATE_PREPARES set to true) which itself has multiple problems:
I could not quickly find out what the default for PDO::ATTR_EMULATE_PREPARES is, apparently "it depends on the driver".
With PDO::ATTR_EMULATE_PREPARES switched on, you cannot use bound parameters in your LIMIT clause anymore
The errors returned from PDO are completely different depending on whether you use client-side or server-side parameter binding, a missing parameter for example causes an SQLSTATE of HY000 with server-side and HY093 with client-side parameter binding. This complicates proper error handling.
There is no way to see the actual query, an ability that can be very useful (essential in my opinion) for debugging.
So, I say go ahead and build your query manually, but in a clean and safe way. To do that you need to understand these concepts:
HTML encoding
In general, the only place where you need htmlspecialchars() is when you pass data (for example from the database) to the browser.
So, change every
$location = trim($_POST['location']);
$location = strip_tags($location);
$location = htmlspecialchars($location);
to
$location = trim($_POST['location']);
There is no need for strip_tags() nor htmlspecialchars() at this point. Form data from the browser arrives on the PHP side without any encoding. Of course, if someone would actually enter some<br>city into the location field, he would not find any rooms, but it will not break anything if you get the rest of your application right.
Also change every
echo "<p>".$result['addressLineOne']." ... </p><br /><hr />";
to
echo "<p>".htmlspecialchars($result['addressLineOne'])." ... </p><br /><hr />";
Otherwise the people entering the data into the database could run a "cross site scripting attack" - maliciously or accidentally.
SQL encoding
When sending data to the database as part of a query, you have to encode it in a way that the database knows that it's variable data and not part of the SQL command.
So, instead of for example
$query .= " AND (`city` LIKE '%".$location."%') ";
you have to write
$query .= " AND (`city` LIKE '%".addslashes($location)."%') ";
this makes sure that if there is a quote character (') inside your $location variable it will be escaped, so it does not end the string at that point.
If you work with a character set other than UTF-8, you should use mysql_real_escape_string() instead of addslashes() but you are probably using UTF-8, so it's just fine.
Furthermore in this case you might want to remove or escape % and _ in the value, because they have a special meaning in a LIKE query.
You have two more problems in your code:
$query = "SELECT * FROM Listings WHERE `bedroom` = ".$bedroom." AND `type` = ".$type."";
Here you not only have to add addslashes() but also the quotes around the value:
$query = "SELECT * FROM Listings WHERE `bedroom` = '".addslashes($bedroom)."' AND `type` = '".addslashes($type)."'";
And here:
$query .= " AND (`price` <= '%".$price."%')";
Obviously the percent signs make no sense here, you clearly meant:
$query .= " AND (`price` <= '".addslashes($price)."')";
Libraries and template engines
Later on you would be well advised using a library or framework that does those things for you (because it's very easy to forget an addslashes() somewhere), but it can't hurt to do it manually at first in order to learn how it works under the hood.
Related
Apologies for the newbie question.
My website has a form.
<form action='' method='get'>
<select id="cSelector" name="cSelector">
<option value=""></option>
<option value="">Show All Items</option>
<option value="Compensation">Compensation</option>
</select>
<input type="submit" value="Submit">
</form>
My querystring, created on form submission, looks like this:
http://website.com/table_example.php?cSelector=Compensation
My query looks like this:
$stmt = $conn->prepare("
SELECT t1.CategoryID,t1.SubCategoryName, t1.CategoryName, t1.SubCategoryID, t2.ItemText from
(SELECT Category.CategoryID,CategoryName, SubCategoryName, SubCategoryID
FROM Category
JOIN SubCategory
ON Category.CategoryID = SubCategory.CategoryID) t1
RIGHT JOIN
(SELECT SubCategoryID, ItemText FROM Item) t2
ON (t1.SubCategoryID = t2.SubCategoryID)
WHERE 1 ".$searchQuery." AND CategoryName = ".$search2." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit,:offset");
The intended result produces a table queried by CategoryName.
My question. Why does this properly execute?
$search2='Compensation';
And this does not?
$search2 = "'".$_GET['cSelector']."'";
Any help would be very much appreciated. And thank you!
You're submitting this form via GET
<form action='' method='get'>
Your line though $search2 = "'".$_POST['cSelector']."'"; is using $_POST
It should be $_GET instead:
$search2 = "'" . $_GET['cSelector'] . "'";`
AFTER OP's CHANGES
This
$search2='Compensation';
and
$search2 = "'".$_GET['cSelector']."'";
are not the same. The top is just a string value. The bottom is a string value wrapped in quotes, so it isn't Compensation it is 'Compensation'.
The core of the issue is actually that you're not exactly sure what the query is. If the two strings sent were identical, they would both run, but they're not. Somehow.
The real need is visibility into your query. So something like
$strQuery = "SELECT t1.CategoryID,t1......";
echo "<pre>$strQuery</pre>";
$stmt = $conn->prepare($strQuery)
Now you can see what it's doing. You're operating blind as it is.
Two additional notes:
You'll hear from everyone that it's a bad idea to put paramaters you're getting from a get or post straight into a SQL query. They're not wrong.
String building for these things is always easier if you're a little more verbose about it. Grab the variable first, as you're going to want to do some processing on it anyway, trimming whitespace, protecting against quotes, etc. Then put it in your query string
The only way I got this to work was if I used the empty. However, this is not what I want. I want to be able to leave something empty if I have to. Does anyone know how I should change the code for this to work?
Edit page:
<form name="homePage" action="update.php" method="POST">
<Strong>Change home title:</Strong>
<p>
<input style="width: 300px;" type="text" name="homeTitleChange" value="<?php echo $homeTitle ?>">
<input type="hidden" name="rowHomeID" value="<?php echo $getHomeID?>">
</p>
<Strong>Change home subtitle:</Strong>
<p>
<input style="width: 600px;" type="text" name="homeSubtitleChange" value="<?php echo $homeSubtitle ?>">
<input type="hidden" name="rowHomeID" value="<?php echo $getHomeID?>">
</p>
<input type="submit" class="btn btn-skin" name="homepage" value="save" />
</form>
Query Page:-
include("../conn.php");
include("../conn.php");
if(isset($_POST['homepage'])){
if(
!empty($_POST["homeTitleChange"])&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowHomeID"])
){
$homeTitleUpdate = $_POST["homeTitleChange"];
$homeSubtitleUpdate = $_POST["homeSubtitleChange"];
$homeEditRow = $_POST["rowHomeID"];
$query = "UPDATE Home SET
title = '$homeTitleUpdate',
subtitle ='$homeSubtitleUpdate'
WHERE homeID = '$homeEditRow' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Success!</p>";
}else{
echo "<p> - Something went wrong</p>";
}
}
}
Thanks!
Precursors:
You have included your connection script twice.
You are including the hidden form field <input type="hidden" name="rowHomeID" value="<?php echo $getHomeID?>"> twice. This is inefficient.
Your form should have enctype='multipart/form-data' . Read Here
Without seeing your MySQL error we can't absolutely diagnose your problem, so instead I will give you the parts I know need to be fixed:
By default PHP string types will hold an empty string '' rather than a NULL value so I don't think your issue is empty values being inserted incorrectly (at least, not as described in your question).
$homeEditRow is the only required value. Because UPDATE table SET column=value WHERE column=<empty> will result in an error (or at the very least, no update).
Therefore replace:
if(
!empty($_POST["homeTitleChange"])&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowHomeID"])
)
with:
if(!empty($_POST["rowHomeID"]){
//run MySQL Update query.
}
Also, if the value is meant to be an integer, you can simply do this:
$homeEditRow = (int)$_POST['rowHomeID']; //force to int.
if($homeEditRow > 0 ){
//run MySQL Update query.
}
Your other two values can be empty if you wish, that's fine.
BUT what these values can not contain is unescaped special characters in MySQL, typically (but by no means exclusively) ` , ', --, # characters.
So, it's best to clean unsafe characters from your user input.
Never Ever Trust User Input to be "safe"
$homeTitleUpdate = mysqli_real_escape_string($conn,$_POST["homeTitleChange"]);
$homeSubtitleUpdate = mysqli_real_escape_string($conn,$_POST["homeSubtitleChange"]);
//assuming to be integer required
$homeEditRow = (int)$_POST["rowHomeID"];
This means any single quotes, or other unsafe characters do not interefere with your query execution. using Prepared statements is much safer than this method and is the recommended way of doing these things, you can use either PDO or MySQLi and there are many, many fine examples on Stack Overflow of these systems.
If you reach this point and you are still having issues, then you need to read what your MySQL error output is saying to you :
//after your query regardless of outcome:
var_dump(mysqli_error($conn));
You may have issues such as you have a primary index column with two non-unique values (etc, etc). But we won't know for sure until you can output the MySQL error.
Finally, be careful with your IF statements checking if the Update Query was carried out because if nothing changed, there was no change to update, MySQL will not run the query, so could potentially return false when everything in fact ran correctly.
Without specifying your errors, we can only assume your problem. Only you can debug your program, so for future notice please execute the following lines of code at the top of your scripts and tell us your errors.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Moving on, your script contains a condition that checks the values at the index in $_POST is !empty() but doesn't wrap around your Query. This meaning, whether or not the values are empty or set, your query will execute.
Assuming you only want to the query to run when there are values set, you can wrap this with an if expression:
// an array of all the index's
$index = ['homeSubtitleChange', 'homeTitleChange', 'rowHomeID'];
// loop through each index and check they're not empty
foreach($index as $_index)
{
if( empty( $_POST[$_index] ) && !isset( $_POST['homepage'] ) )
{
// if empty - halt the program with an error
die("Expected POST index: $_index or homepage.");
}
}
unset($_index); //cleanup
// if it got here - all index's have values
// as Martin said in the comments, I assume you can wrap mysqli_real_escape_string()
// and intval() ensuring the value is type (int) to protect
// your database against SQL attacks
$subtitle = mysqli_real_escape_string($conn, $_POST[$index[0]]);
$title = mysqli_real_escape_string($conn, $_POST[$index[1]]);
$row_id = intval($_POST[$index[2]]);
// consider upgrading to a PDO driver and using prepare() statements
// this SQL statement is prone to SQL injections
$sql = "UPDATE Home SET title = '$title', subtitle = '$subtitle' WHERE homeID = '$row_id'";
if( mysqli_query( $conn, $query ) )
{
die("Success.");
}
die("Failed.");
If I understand correctly, you want to allow empty string as input.
If so, what you want is isset() instead of !empty().
So, this part in your code:
!empty($_POST["homeTitleChange"])&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowHomeID"])
replace it with this:
isset($_POST["homeTitleChange"],$_POST["homeSubtitleChange"],$_POST["rowHomeID"])
and you're good to go.
As everyone else has said, please sanitize your user input; putting it directly into the database like that is very unsafe.
As for your question, from what I can understand you are trying to work out to make sure the values are set, but you also want to be able to pass an empty string!?
If so, I think you want isset.
//...
if(
isset($_POST["homeTitleChange"])&&
isset($_POST["homeSubtitleChange"]) &&
isset($_POST["rowHomeID"])
){
//...
This will make sure you POST values are set, which they should be anyway if they submitted the form; however it will also return true if the $_POST["rowHomeID"] = 0, which may not be what you want, so you may want to go back to using !empty for that which will mean it can't be an empty string or equal to 0.
I have a dropdown lists which the default value is selected. If there is a value there the if statements allow an update to the data. If no value then instead a whole row will be inserted. It works if I hard code the third value as 1. However when I set this to $category_of_taxom1 the insert doesn't work. The Update works fine, so If I manually create the record within the DB, I can update it via the update SQL shown below. But if I try INSERT no luck? (I Have hard coded the first 3 items to be inserted, the third should be the variable mentioned above.
I have this select list
<select name="categorySelect1fromDB" >
<option value ="">EMPTY</option>';
<option value="1" <?php echo ($category_of_taxom1 == 1)?"selected":""; ?>>A</option>
<option value="2" <?php echo ($category_of_taxom1 == 2)?"selected":""; ?>>B</option>
<option value="3" <?php echo ($category_of_taxom1 == 3)?"selected":""; ?>>C</option>
<option value="4" <?php echo ($category_of_taxom1 == 4)?"selected":""; ?>>D</option>
</select>
And this set of statements.
if(isset($_POST['save']))
{
$category_of_taxom1 = $_POST['categorySelect1fromDB'];
$number_of_taxom1 = $_POST['number_of_taxom1'];
if (!empty($category_of_taxom1)){ //This is the value fromDB if not empy then do below else do last
pg_query("UPDATE record_tbl SET category_of_taxom ='$category_of_taxom1', number_of_taxom ='$number_of_taxom1' WHERE sheet_id = '$sheet_id' AND line = 1");
echo "Updated!";
} else
{
pg_query("INSERT INTO record_tbl (line, taxom_id, category_of_taxom, number_of_taxom, sheet_id) VALUES (1,1,'$category_of_taxom1','$number_of_taxom1','$sheet_id')");
echo "New Record ?Saved!";
}
}
This is an example of a working pgsql line I use else where in my site:
$sql8 = "INSERT INTO record_tbl (line, taxom_id, category_of_taxom, number_of_taxom, sheet_id) VALUES (8,8,'$_POST[gammarus_numbers]','$_POST[countgammarus]','$sheetid')";
$result = pg_query($sql8);
The datatype for the field 'category_of_taxom' is most likely set to varchar, meaning it should have quotes around the value when using INSERT. So you can either:
1) Change the datatype of category_of_taxom to integer in your database
2) Include quotes around the value in your INSERT statement:
('1','1','1','$number_of_taxom1',$sheet_id)
Related documentation:
mysql - quote numbers or not?
I should probably delete this question: The quotes were correct, I needed them on each variable. However because the code was so long, i couldnt post it all on here. I had accidentally called that variable twice. So at one point of time it does have something in, but within the same code it may also not. So i ended up having to rename my variable. Not really a good answer, but going to delete it anyway. As this will be too narrow for anyone else.
I'm an absolute noob to programming and over the past 10 days or so I have been building a 'buy sell trade' website for things.
Anyway I have got to the point where I now have the ability for people to register, post ads and reply to them... but now I want to have a page where they can search through the adverts.
The search form works on 3 fields, 'make', 'model' and 'caliber' (site is for guns)
<form action="" method="get" autocomplete="off">
I'm looking for a
<input type="text" name="make" class="autosuggestmake" placeholder="Manufacturer"/>
<div class="dropdown">
<ul class="resultmake"></ul>
</div>
<input type="text" name="model" class="autosuggestmodel" placeholder="Model"/>
<div class="dropdown">
<ul class="resultmodel"></ul>
</div>
in
<select name="caliber" >
<option value="*">(Caliber) Any</option>
<option value=".177">.177</option>
<option value=".20">.20</option>
<option value=".22">.22</option>
<option value=".25">.25</option>
</select>
<input type="submit" value="Search" />
This is posted as GET data which I 'catch' with this code:
$advert = new Advert;
if (empty($_GET) === true){
$adverts = $advert->fetch_all();
} else {
$search_make = $_GET['make'];
$search_model = $_GET['model'];
$search_caliber = $_GET['caliber'];
$adverts = $advert->fetch_results($search_make, $search_model, $search_caliber);
}
My fetch_results query is this:
class Advert {
public function fetch_results($search_make, $search_model, $search_caliber) {
global $pdo;
$search_caliber = mysql_real_escape_string($search_caliber);
$search_make = mysql_real_escape_string($search_make);
$search_model = mysql_real_escape_string($search_model);
if (empty($search_make) === true){
$search_make = "*";
}
if (empty($search_model) === true){
$search_model = "*";
}
$query = $pdo -> prepare("SELECT * FROM `adverts` WHERE make = '$search_make' AND model = '$search_model' AND caliber = '$search_caliber'");
$query -> execute();
return $query -> fetchAll();
}
On my last question someone told me to start using PDO, so I did :)
My problem is when someone fills in the make field on my form and nothing else it will return nothing. I thought if the get variables were blank I would append a * and it will return anything but this is not the case :( I've been searching but I think my problem is I don't know the correct words to search to find the cure for my problem...
Any help would be greatly appreciated.
Having implemented a site with this myself, I strongly recommend Sphinx. This is what craigslist uses. It is simple enough for your needs, yet powerful enough to grow with you.
Another alternative is ElasticSearch, which I'm told is very good as well.
There are two approaches you can take. One is to rewrite the query in php based on the search conditions.
The other is a SQL solution:
SELECT *
FROM `adverts`
WHERE ('$search_make' = '' or make = '$search_make') AND
('$search_model' or model = '$search_model') AND
('$search_caliber' or caliber = '$search_caliber');
However, if the table has indexes on the columns, then this query probably will not use the indexes. Writing the php to include only the clauses with values creates a more efficient query.
Either you let your users browse "all" -- Use case = some collector looking for odd items.
Or you have a "Search By" pull down and make your users choose at least one of the search categories.
You could just send an error message if all the search criteria are blank -- but this tends to annoy users more than leading them through a set of search option screens.
I'm currently building my first database in MySQL with an interface written in PHP and am using the 'learn-by-doing' approach. The figure below illustrates my database. Table names are at the top, and the attribute names are as they appear in the real database. I am attempting to query the values of each of these attributes using the code seen below the table. I think there is something wrong with my mysql_query() function since I am able to observe the expected behaviour when my form is successfully submitted, but no search results are returned. Can anyone see where I'm going wrong here?
<form name = "search" action = "<?=$PHP_SELF?>" method = "get">
Search for <input type = "text" name = "find" /> in
<select name = "field">
<option value = "Title">Title</option>
<option value = "Description">Description</option>
<option value = "City">Location</option>
<option value = "Company_name">Employer</option>
</select>
<input type = "submit" name = "search" value = "Search" />
</form>
$query = "SELECT Title, Descrition, Company_name, City, Date_posted, Application_deadline
FROM job, employer, address
WHERE Title = $find
OR Company_name = $find
OR Date_posted = $find
OR Application_deadline = $find
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id";
There seems to be at least four problems:
You don't have quotes around $find, i.e. WHERE Title = '$find'.
You don't seem to be using mysql_real_escape_string (or did you just omit that code in your question for brevity?)
You spelled Description incorrectly.
AND has higher precedence than OR so you probably want parentheses in your expression:
WHERE (Title = '$find'
OR Company_name = '$find'
OR Date_posted = '$find'
OR Application_deadline = '$find')
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id"
I suspect that one or more of these are the reason why it's not working. However to be sure you should post more of your code and your table structure.
Another point is that you are using the old ANSI-89 join syntax. I would recommend using the newer syntax added in SQL-92 (FROM a JOIN b ON ...). This would have prevented you from making the fourth error, as well as having numerous other advantages over the older syntax.
Also try using mysql_error to find out what the exact error message is. And please include the message in your question.
If you like to learn by doing then learn by doing it in PDO and bind the parameters. This is the safe and correct way to do it these days.
Use single quotes for values in where clause.
Try this one:
$fields= array('Title','Company_name', 'Date_posted','Application_deadline');
if(!in_array($_GET['field'],$fields)) die(); // do some error handling here
$query = "SELECT Title, Descrition, Company_name, City, Date_posted, Application_deadline
FROM job, employer, address
WHERE
$field = '".mysql_real_escape_string($_GET['find']) ."'
AND job.employer_id_job = employer.employer_id
AND job.address_id_job = address.address_id";
If single quotes isn't your only problem (it is certainly part of it), check the return of mysql_error().
Check the code samples here:
http://www.php.net/manual/en/function.mysql-query.php
I would suggest also using ezSQL to do all your query handling, it's easy to drop into your code and makes all the processing easy, just include the db info in a config file, include the classes for ezSQL in the config file, setup a global call to the class like
$db = new ez_SQL();
then in your referencin php files, just do this
global $db;
$results = $db->query("SELECT statment", ARRAY_A);
you can get ezsql from: http://justinvincent.com/ezsql