如何解决'试图获得非对象错误的属性'& php代码中的'未定义变量:id'?

时间:2015-12-11 11:05:43

标签: php

我在以下代码中为3行获取'试图获取非对象错误的属性'。如何解决此问题?我的完整代码是:

$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);

此外,我收到以下代码的“未定义变量:id”错误:

$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);

2 个答案:

答案 0 :(得分:0)

你能告诉我你的JSON数据吗?第二种选择尝试这个

$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);

答案 1 :(得分:0)

在对它们执行任何操作之前,您需要检查变量是否存在。对于第二个问题,您不能保证在URL上传入了ID,所以:

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

对于第一个问题再次你不能保证来自“php:// input”的是一个JSON字符串或json_decode工作。将代码分解为不同的阶段,并在继续之前测试每个代码是否有效,而不是将它们连接成一行。

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
}