PHP Warning: mysqli::query(): Couldn't fetch mysqli

Hello,

I am trying to add a comment section to my website, however, when I try to insert the comment along with some other information to the database, it fails with the error:

PHP Warning: mysqli::query(): Couldn't fetch mysqli in /var/www/html/index.php.

Do you have any idea as to what is causing this? It is just like all the other SQL quries on my site, but this is the only on that is giving me an error.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
    if(isset($_POST["comment"]) && isset($_SESSION["discord_username"])){
        $post_time = time();
        $discord_c_id = $_SESSION["discord_user_id"];
        $discord_real_username = $_SESSION["discord_username"];
        $comment = $_POST["comment"];
        $sql = "INSERT INTO comments (discord_id, discord_username, post_time, comment) VALUES ('${discord_c_id}', '${discord_real_username}', '${post_time}', '${comment}')";
        $result = $conn->query($sql);
      }

header("Location: /");
die();

That error usually means that the variable holding the connection no longer has a connection in it.

Is the php error coming from the posted code or is it after the header() redirect? I would temporarily comment out the redirect to see if the symptom changes.

Next, why are you putting external, unknown, dynamic values directly into an sql query? You should use a prepared query for those type of values.

Your error appears to be eminating from your index page, not from this one.

1 Like

Thanks, I’ll have a closer look at the index page.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.