0

I am retrieving data from a database in android so created a php file as below.

    <?php

 $db_host  = "localhost";
 $db_uid  = "root";
 $db_pass = "";
 $db_name  = "abc";         
 $db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
 mysql_select_db($db_name);
 $sql = "SELECT * FROM people WHERE  birthyear > '". $_POST["birthyear"]."'";
 $result = mysql_query($sql);
 while($row=mysql_fetch_assoc($result))
  $output[]=$row;
 print(json_encode($output));
 mysql_close();   
?>

Now when i run it in the browser as localhost/script.php error is thrown and the output is displayed as below

Notice: Undefined index: birthyear in C:\xampp\htdocs\jasonscript.php on line 14 [{"id":"1","name":"m","sex":"1","birthyear":"1989"},{"id":"2","name":"a","sex":"1","birthyear":"1986"},{"id":"3","name":"b","sex":"0","birthyear":"1986"}]

Please tell me how to correct my code.

4

3 回答 3

2
$output[]=array("key"=>$row['field_name'],"key1"=>$row['field_name2']);

像这样存储数组

于 2013-05-08T10:42:30.827 回答
1

您直接插入$_POST["birthyear"]查询中,这使您容易受到 SQL 注入的攻击。立即停止这样做!

这也是你得到错误的原因。当您在浏览器中直接调用脚本时,将带有 GET 请求,并且不会有任何可用的 POST 变量。所以你的$_POST数组不会有一个密钥birthyear,因此它会警告你。

你应该从类似的东西开始

<?php
$by = isset($_POST["birthyear"]) ? $_POST["birthyear"] : "";
if (empty($by)) {
  echo 'Invalid birthyear';
  exit;
}

//SANITIZE YOUR BIRTHYEAR HERE
//in this case, probaly check for a integer between 1900 and 2100 or something.
//Although just an int could be enough to prevent injection

if (!is_int($by)) {
  echo 'You failed to provide a valid year';
  exit;
}

$sql = "SELECT * FROM people WHERE  birthyear > '". $by."'";

//execute the code 
?>

虽然上面的代码是安全的,你应该检查一下mysqlibound parameters中使用的准备语句PDO

于 2013-05-08T10:45:09.303 回答
0

您可能无法通过帖子正确发送值。尝试print_r($_POST);查看您实际发送的内容

你仍然会得到所有的结果,因为每年都是> ''

于 2013-05-08T10:45:55.773 回答