SELECT * FROM $ _POST [] - PHP mySQL格式
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...) }); });
需要帮助格式化mySQL查询字符串。 以下查询返回“解析错误,期待T_STRING或T_VARIABLE” p>
PHP: p>
&lt;?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)或die(mysql_error());
$ row = mysql_fetch_assoc($ result);
echo json_encode($ row);
?&gt; ;
代码> PRE>
jQuery的: p>
$( '#profiles_desktops')上单击(函数(){
。 $ .post(“php / loadProfile.php”,{plant_code:selectedSite,tab:“profiles_desktops”},function(result){(在这里做点什么......)});});
code>
div>
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'])."'";
Query should be:
"SELECT * FROM ".$_POST['tab']." WHERE plant_code =".$_POST['plant_code']
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 :]
Your concatenations in $query
declaration are wrong.
$query = "SELECT * FROM " . $_POST['tab'] . "WHERE plant_code = '" . mysql_real_escape_string($_POST['plant_code']) . "'";
would suffice.
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;