PHP & MySQL syntax problem.

by 6 replies
7
Hello,

Here's the problem:

$_POST['location'] is being sent from a previous page.

Here's my code:

Code:
$query = ('SELECT * FROM curr_vacs WHERE job_location = "$_POST['location']"');
When I load the page, nothing shows up. If I change it to:

Code:
$query = ('SELECT * FROM curr_vacs WHERE job_location = "ATOWN"');
It seems to work just fine.

To test it, I was using:

Code:
$location="ATOWN";

$query = ('SELECT * FROM curr_vacs WHERE job_location = "$_POST['location']"');
.... nothing.

I'm still VERY NEW to php, but cannot figure it out.

Any advice is greatly appreciated.

Cheers,

Andy.
#programming #php
  • Change it to

    $query = "SELECT * FROM curr_vacs WHERE job_location = '{$_POST[location]}'";


    The string data in the query is bounded by single quote ' character and not double quote. When parsing the PHP the string in double quotes is parsed for variable data. The { } within the double quoted string helps define the variable. The element in the array within the double quoted string does not contain the otherwise needed quote. Varying syntax of differing coding systems, got to love it.
    • [ 1 ] Thanks
  • Sir!! Thank you. Great help!!

    I can only hope that one day I'll fully understand the explanation, but for now, I'm just thrilled that a php issue that is simple to others will not taunt my nightmares.

    Thank you again.
    • [1] reply

    • When testing (not on live production servers) remember to liberally use echo commands.

      $query = "SELECT * FROM curr_vacs WHERE job_location = '{$_POST[location]}'";

      then

      echo $query;

      The page output will be your SQL query and you can run it in a MySQL server to see what actual errors are output.
  • also, that code as-is is vulnerable to sql injection, you might want to sanitize your data inputs.
    • [1] reply
    • That depends on how $_POST['location'] is set. If it is a textfield then yes the data should be "sanitized" before using it in the SELECT. If it is a radio, checkbox or a select list then the data is already sanitized because the value is from a known set. To sanitize the data you would use mysql_real_escape_string() and addslashes();
      • [1] reply
  • [DELETED]
  • Banned
    [DELETED]

Next Topics on Trending Feed