简体   繁体   中英

how to solve 'Trying to get property of non-object error' & 'Undefined variable: id' in php code?

I am getting 'Trying to get property of non-object error' for the 3 lines in the following code. What can be done to resolve this issue? My full code is:

$con=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$data = json_decode(file_get_contents("php://input"));

$name = mysqli_real_escape_string($con, $data->name); //ERROR FOR THIS LINE
$address = mysqli_real_escape_string($con, $data->address); //ERROR FOR THIS LINE
$sql = "INSERT INTO friend_data(name,address) values ('$name','$address')"; //ERROR FOR THIS LINE

if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Record Added";
mysqli_close($con);

Also I am getting 'Undefined variable: id' error for the following code:

$con=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$id = $_GET['id']; //ERROR FOR THIS LINE
$sql = "delete from friend_data where id= '$id'";

if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Record Removed";
mysqli_close($con);

Can you show me your JSON data. And for second option try this

$id = $_GET['id'];
$con=mysqli_connect("localhost","root","","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "delete from friend_data where id= '$id'";

if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Record Removed";
mysqli_close($con);

You need to check that the variables are there before you do anything with them. For the second question you can't guarantee that id was passed in on the URL so do:

if (isset($_GET['id])) {
   //do something
} else {
   //show an error
}

for the first question again you cant guarantee that what came from "php://input" was a JSON string or that json_decode worked. Break the code into different stages and test that each worked before continuing rather than concatenating it all into a single line.

if (($content = file_get_contents("php://input")) !== FALSE) {
   $data = json_decode($content);
   if (($data != null) && (is_object($data))) {
     //do your stuff
   } else {
     //error
   }
} else {
   `//error
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM