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.

3 Answers 3

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

store array like this

Sign up to request clarification or add additional context in comments.

1 Comment

I am fine with the output . need to know why Notice: Undefined index: birthyear in C:\xampp\htdocs\jasonscript.php on line 14 is getting displayed.
1

You are directly inserting $_POST["birthyear"] in your query which makes you vulnerable to SQL injection. Stop doing it right now!

That is also why you get the error. When you directly call the script in your browser, that will be with a GET request and there wont be any POST variables available. So your $_POST array wont have a key for birthyear and thus it warns you about it.

You should start with something like

<?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 
?>

Although the above code is safe, you should check out bound parameters like used in mysqli prepared statements or PDO

1 Comment

+1 definitely should sanitize to avoid them dumping your whole database out inadvertently...
0

you probably failed to send the values trough post properly. try print_r($_POST); to see what you are actually sending

you still get all results because every year is > ''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.