Pergunta

i am writing a java code that http post with a parameter.that parameter is a long variable that convert to string.

ArrayList<NameValuePair> parameters =new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("MAX_ID", String.valueOf(maxNewsId)));
        String result = CustomHttpClient.executeHttpPost(NewsUrl,parameters);

and i want write a php code at the server. that code should get that long number and connect to Data base and select rows that have id greater than that parameter. i write this code but not working. what should i do?

  <?php
 $db_host  = "localhost";
 $db_uid  = "**********";
 $db_pass = "**********";
 $db_name  = "**********"; 


 $db_con = mysql_connect($db_host,$db_uid,$db_pass,$db_name) or die('could not connect'); 
 mysql_select_db($db_name);
 $maxId = $_POST['MAX_ID'];
 mysql_query("set names utf8");
$sql = "SELECT * FROM News where Nid> ".mysql_real_escape_string($maxId);
$result = mysql_query($sql);

while($row=mysql_fetch_assoc($result))
{
    $output[]=$row;

}
print(json_encode($output));
 mysql_close();   

?>
Foi útil?

Solução

A few notes about your code:

First... please don't use mysql_query anymore. Use mysqli_query or PDO. In newer PHP versions mysql_xxx is deprecated and you should use the alternative.

Second... your code is very susceptible to attack. When you use a POST or GET variable you should check if it does not contain harmful code. If your MAX_ID could only be a number i would suggest the following (note the intval-part):

$maxId = 0;
if (isset($_POST['MAX_ID'])) $maxId = intval($_POST['MAX_ID']);

It also checks if MAX_ID is not set (if so your $max_id is 0) and $maxId could only result in a number.

And last... because with above $maxId could only result in a number you don't need the mysql_real_escape_string. So this would be enough:

$sql = "SELECT * FROM News where Nid > ".$maxId;

(please note the warning at the top of the manual of this function about mysql_xxx being deprecated).

Outras dicas

if you want greated than: you should change the "<" see in bold

$sql = "SELECT * FROM News WHERE Nid < ".mysql_real_escape_string($maxId);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top