2

Need help formatting a mySQL query string. The following query returns "parse error, expecting T_STRING or T_VARIABLE"

PHP:

<?php


include 'db_connect.php';

mysql_select_db($databaseName, $con);

$query = "SELECT * FROM .$_POST['tab']. WHERE plant_code = .$_POST['plant_code']";

$result = mysql_query($query) or die (mysql_error());

$row = mysql_fetch_assoc($result);

echo json_encode($row);

?>

jQuery:

$('#profiles_desktops').click(function(){
                $.post("php/loadProfile.php", {plant_code : selectedSite, tab : "profiles_desktops"}, function(result){ (do something here...) });  });
Ben Bernards
  • 187
  • 1
  • 3
  • 12

5 Answers5

4

DO NOT DO THAT! it's wide open to SQL injection attacks. For god sake, validate and escape your input.

at the very least, rewrite it to:

$query = "SELECT * FROM `".mysql_real_escape_string($_POST['tab'])."` WHERE plant_code = '".mysql_real_escape_string($_POST['plant_code'])."'";
Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • Yup, this did it. (Note those are NOT single quotes, but are...what...back-quotes? Hiding under the ~ on my keyboard.) – Ben Bernards Apr 12 '12 at 23:08
  • They're called backticks, and you can read a bit more about them in this thread: http://stackoverflow.com/questions/261455/using-backticks-around-field-names – Not_a_Golfer Apr 12 '12 at 23:18
1

Query should be:

"SELECT * FROM ".$_POST['tab']." WHERE plant_code =".$_POST['plant_code']
Cassie Smith
  • 503
  • 3
  • 12
1

The periods (.) in your query are unnecessary because you didn't break the quotes. Either of these should work:

$query = "SELECT * FROM $_POST['tab'] WHERE plant_code = $_POST['plant_code']";

or

$query = "SELECT * FROM " . $_POST['tab'] . " WHERE plant_code = " . $_POST['plant_code'];

Edit: This is, of course, not addressing the giant injection security holes :]

orourkek
  • 2,091
  • 15
  • 22
0

Your concatenations in $query declaration are wrong.

$query = "SELECT * FROM " . $_POST['tab'] . "WHERE plant_code = '" . mysql_real_escape_string($_POST['plant_code']) . "'";

would suffice.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

Should be:

$query = "SELECT * FROM ".$_POST['tab']." WHERE plant_code = ".$_POST['plant_code'];

needed to have the php variable surrounded by double quotes (and leave the last one off, since you are ending with a variable, or instead of double quotes, leave out the dots because PHP will see it's variables and convert them to the values before the query runs. Also, sql doesn't like bracketed array variables for some reason. Try putting all your values in variables which is also much nicer to read:

$tab = $_POST['tab'];
$plant = $_POST['plant_code'];
$query = "SELECT * FROM ".$tab." WHERE plant_code = ".$plant;
Ryan
  • 3,153
  • 2
  • 23
  • 35