0
Fatal error: Call to a member function query() on a non-object in comments/comments.inc.php on line 10

My php code looks like this:

<?php

function setComments($conn) {
    if(isset($_POST['commentSubmit'])) {
        $uid = $_POST['uid'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
        $result = $conn->query($sql); 
    }

}

I really don't understand how to fix this problem, as I'm trying to learn php. Any help is welcome, thanks.

The page with this code is an include for another page.

The other include i have has its code that looks like this:

<?php

$conn = mysqli_connect('localhost','username','password','database');

if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}

both of these includes are called on a main page called index.php.

WillingLearner
  • 7,106
  • 6
  • 34
  • 51
  • how did you call this function setComments() it seems that your conn object is null ? – CodeIsLife Mar 19 '17 at 18:56
  • The `$conn` variable is not an object. You must not be passing an object to this function. Also, read this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Alexander O'Mara Mar 19 '17 at 18:56
  • This means that `$conn` is not an object, so you cannot call `->query()`. Before your if statement, run `var_dump($query); die();` to see what you are actually passing into `setComments` – Gravy Mar 19 '17 at 18:57
  • Your function isn't defining `$conn` so function scope means it can't be accessed. Pass `$conn` as an argument – Machavity Mar 19 '17 at 18:59
  • $conn = mysqli_connect('localhost','username','password','database'); this is set in another include document and both that page, and the current page with this problem script, are called simultaneously into a separate page. – WillingLearner Mar 19 '17 at 19:50

0 Answers0