Using a PHP variable in a mysql query

I am trying to create a query which allows a user to look up property by type using a dropdown list. I am using a variable in the SELECT query to check if there are any records in the database and print them on screen.
The following code accepts a variable (selected from a dropdown list) and uses it in a query. In this example the variable’s value is “type” – without the quotes.

Eg:The PHP code:
$type = $_POST[‘type’]; (I am storing the option from the ‘type’ drop down list in this variable)

The queries i have tried:
$query = mysql_query(“SELECT * FROM tbl_property WHERE type=’$type’ “);
$query = (“SELECT * FROM tbl_property WHERE type==”.””.$type."");
$query = “SELECT COUNT() FROM tbl_property WHERE type==’" . $type . “’”;
$query = mysql_query("SELECT COUNT(
) FROM tbl_property WHERE type=”" . $type."");

$result = mysql_query($query)or die("Error in query: ". mysql_error());

The HTML form:

Flat Terraced house Villa House of Character

I would really appreciate any help as i am really stuck on this problem. Thanks.

Did you check if $_POST[‘type’] is submitted from the form and is available in your php? Your first version of query should work fine. Also, do you see any error message returned by mysql_erorr() ?


Not fully understanding the exact nature of your database, I thought perhaps this might help. Queries for data that does not have an exact match must be enclosed in the %findthis% format. In the event that this may be your problem, i include the following two illustrations. The first is a direct phpMyAdmin query. The second is the same query converted into a php format.

Hope maybe this helps.

Grace and mercy always,

Direct query of data base

SELECT article_id , article_author , article_title
FROM article_master
WHERE article_author LIKE CONVERT( _utf8 ‘%rmharrington%’
USING latin1 )
COLLATE latin1_swedish_ci
LIMIT 0 , 30

PHP code for same input

SQL query:
$sql = ‘SELECT article_id, article_author, article_title FROM article_master WHERE article_author LIKE CONVERT(_utf8 ‘%rmharrington%’ USING latin1) COLLATE latin1_swedish_ci’;

$result = mysql_query(“SELECT * FROM tbl_property WHERE type = ‘$type’”);
if($row = mysql_fetch_array($result, MYSQL_ASSOC))
// do something with $row[‘type’];
else { die( "Error in query: " . mysql_error() ); }


Sponsor our Newsletter | Privacy Policy | Terms of Service