Search code examples
phpmysqlmysqli

Warning: mysqli_close(): Couldn't fetch mysqli


I'm getting this error:

Warning: mysqli_close(): Couldn't fetch mysqli in sendinvoice.php on line 54

Here is my code:

    <?php
include 'dbconfig.php';
ob_start();

$taxcb = $_POST['taxcb'];
$taxrate = $_POST['taxrate'];
$bcctocb = $_POST['bcctocb'];
$bcctotxt = $_POST['bcctotxt'];
$duedate = $_POST['duedate'];
$issuedate = $_POST['issuedate'];
$additemscb = $_POST['additemscb'];
$additemname = $_POST['additemname'];
$additemprice = $_POST['additemprice'];
$q = $_POST['rowid'];

$sql="SELECT * FROM clients WHERE id = '".$q."'";

$result = mysqli_query($conn,$sql);

while($row = mysqli_fetch_array($result)) {


$to = $row[email];
$subject = "Invoice Test " . date('m/d/Y h:i:s a', time());
include 'invoice.html';
$message = ob_get_clean();

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <[email protected]>' . "\r\n";
if ($bcctocb == "y"){
$headers .= 'BCC: ' . $bcctotxt . "\r\n";
}

mail($to,$subject,$message,$headers);

$sql = "UPDATE clients SET last_billed='" . date("Y-m-d H:i:s") . "' WHERE id=" . $q;

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

}

mysqli_close($conn);

?>

I only want it to update the MySQL entry if everything was successful. I suspect it's an error with having two MySQL things going on at once, is there a more efficient way to combine them?


Solution

  • It's difficult to tell with the indentation, but in some cases you will close the connection twice...

    $conn->close();
    
    }
    
    mysqli_close($conn);
    

    These will both close the connection, so the second one will fail. Probably easier to remove the $conn->close(); as it will always fall through to the second close.