Page 1 of 1

Error: Trying to get property of non-object

PostPosted: 14. October 2015 14:15
by remmargorp
Hi all,

The following code index.php is stored at C:\xampp\htdocs\xss\3\index.php.
When I try to run it, I'm getting this error. Please let me know how to fix this issue.

URL in my computer
Code: Select all
http://localhost/xss/3/


Error Message
Code: Select all
Notice: Trying to get property of non-object in C:\xampp\htdocs\xss\3\index.php on line 75


Line 75 of C:\xampp\htdocs\xss\3\index.php
Code: Select all
if ($result->num_rows > 0) {


Related code:
Code: Select all
<?php
$sql = "SELECT id, comment FROM comments";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td style='width:35%;padding:10px'>Comment #".$row["id"]."<br /><hr />".$row["comment"]."<br /></td></tr>";
    }
} else {
    echo "<tr><td style='width:35%'>No Comments!</td></tr>";
}
$conn->close();
?>


Please let me know if you need more info to resolve this issue.

Re: Error: Trying to get property of non-object

PostPosted: 14. October 2015 14:50
by Altrea
Where did you initialize $conn?

Re: Error: Trying to get property of non-object

PostPosted: 14. October 2015 15:04
by Nobbie
You do not evaluate $result, it could be NULL.

Re: Error: Trying to get property of non-object

PostPosted: 14. October 2015 15:19
by Altrea

Re: Error: Trying to get property of non-object

PostPosted: 14. October 2015 17:54
by remmargorp
Altrea wrote:Where did you initialize $conn?


Thanks Altrea for your feedback. I hope this will answer your question.
Code: Select all
[code]$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['clear']))
{
   $sql = "TRUNCATE TABLE comments";
   if ($conn->query($sql) === TRUE)
   {
      echo "Table Cleared";
   } else {
      echo "Error: Unable to Clear Table". $conn->error;
   }
}[/code]

<?php
if (isset($_POST['comment']))
{
   if ($conn->query($sql) === TRUE)
   {
      echo "New record created successfully";
   } else {
      echo "Error: Unable to add comment";
   }
}
?>

Re: Error: Trying to get property of non-object

PostPosted: 14. October 2015 17:57
by remmargorp
Nobbie wrote:You do not evaluate $result, it could be NULL.


Thanks Nobbie for your input. I'm new to this. Please let me know how to evaluate it.

Re: Error: Trying to get property of non-object

PostPosted: 14. October 2015 18:34
by Nobbie
remmargorp wrote: Please let me know how to evaluate it.


With an if-clause and a comparison.

Am i right, that you have no idea about programming PHP? I cannot teach you PHP, you have to learn it on yourself.