0

After making some modifications to my existing script, I created an error:

Notice: Trying to get property of non-object...

I am trying to figure how to identify if the variable $result is an object so I don't get this error (I am getting the error on this particular line if ($result-> num_rows > 0) { ). Here is what have:

<?php 
$sql = "SELECT * FROM input WHERE id =".$_GET["id"]; 
$result = mysqli_query ($conn,$sql);

if ($result-> num_rows > 0) { 
    while($row -> $result->fetch_assoc()) { 
        $myid = $row["id"] ;
        $sql2 = "SELECT * FROM output WHERE question_id = $myid ORDER BY date DESC";
        $result2 = $conn->query($sql2);
        $sql3 = "SELECT COUNT(*) as rowCount FROM output WHERE question_id = '".$myid."'";

        $result3 = $conn->query($sql3);
        $rowCount= $result3->fetch_assoc();
?>

How can I tell beforehand if this is an object or not?

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
harishk
  • 418
  • 5
  • 21
  • 2
    I think you had run the query in procedural way and getting data in Object-oriented way is the reason for issue. – Sasikumar Sep 15 '16 at 04:12
  • $result is not an object because your query failed, you need to debug that –  Sep 15 '16 at 04:14
  • 1
    As a side advice, don't you ever concatenate a GET parameter to a query without cleaning it or using prepared statements. Search for mysql injection – Mark E Sep 15 '16 at 05:03

2 Answers2

0

First of all, do you have the variable $conn initialized any where in the code before that?
Second, you want to make your while loop like this:
while($row = $result->fetch_assoc()) { ... }

Paul Karam
  • 4,052
  • 8
  • 30
  • 53
  • "Yes" , i have $conn included in the script. and "no" changing the -> to = didn't gave any clue.. – harishk Sep 15 '16 at 04:18
  • guess what changing -> to = in `if ($result-> num_rows > 0) {` made `num_rows` a constant.. – harishk Sep 15 '16 at 04:24
  • I am not sure, but could it be the space after the $result-> num_rows, and about the $result = $row->fetch_assoc() I got it from here: http://php.net/manual/en/mysqli-result.fetch-assoc.php – Paul Karam Sep 15 '16 at 04:29
  • earlier i thought the same, whether $ sign infront of num_rows can be the reason but it didn't instead i even changed the -> to = but it kinda allowed space for new errors.. – harishk Sep 15 '16 at 04:35
  • 1
    I suggest to debug your code, try to see the $results variable what it contains before executing the loop, like just comment out all the code after $result = mysqli_query($conn,$sql), check it, and see where your code is breaking. – Paul Karam Sep 15 '16 at 04:42
0

You can use to find content is array or object :

is_object() to find object 
is_array() to find array 

$sql = "SELECT * FROM compt WHERE id =1"; 
$result = mysqli_query ($conn,$sql);

if ($result->num_rows > 0) { 
    while($row = $result->fetch_assoc()) { 

    }
    }
Basant Rules
  • 785
  • 11
  • 8