The following code accepts a variable (selected from a radio button list) and uses it in a query. In this example the variable's value is "Reference" -- without the quotes.
<?php
require_once ('../mysql_connect.php'); // Connect to the database.
$var1 = ($_POST['location']);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT number FROM files WHERE location = '$var1'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
echo "The value of \$var1 is: <b>$var1</b><br>"; // display the value of the variable -- for debugging purposes.
echo "The value of \$query is: <b>$query</b><br>"; // Display the query terms -- for debugging
echo "The value of \$query is: <b>\"$query\"</b><br>"; //My attempt to add double quotes -- for debugging.
echo "The value of \$result is: <b>$result</b>"; // Display the value of $result -- for debugging.
?>
</form><!-- End of Form -->
The code returns the following:
The value of $var1 is: Reference
The value of $query is: SELECT number FROM files WHERE location = 'Reference
The value of $query is: "SELECT number FROM files WHERE location = 'Reference
The value of $result is: Resource id #4
The query fails -- presumably because the term 'Reference does not have a trailing single quote. (Please see the end of lines 2 and 3). Also note that line 3 only has an opening double quote -- before the word SELECT.
Things I've tried:
$query = "SELECT number FROM files WHERE location = '.$var1'";
$query = "SELECT number FROM files WHERE location = '$var1'";
$query = "SELECT number FROM files WHERE location = '" . $var1 . "'";
$query = "SELECT number FROM files WHERE location ='$POST[location]'";
$query = sprintf("SELECT number FROM files WHERE location = '%s'",
$var1;
and supplying the variable with additional quote(s)
$var1 = ($POST['location']);
$adquote = ''$var1'';
and a whole bunch of other things that failed miserably.
Any help much appreciated!