skip to Main Content

I am trying to make a delete.php file to work, it suppose to delete file uploaded against db. Can someone help me with what I am doing wrong here?

Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, it is on line 7.

This is the code:

<?php

include "dbconnect.php"; // Using database connection file here

$id = $_GET['id']; // get id through query string

$del = mysqli_query($db,"delete from tbl_files where id = '$id'"); // This is line 7, delete query

if($del)
{
    mysqli_close($db); // Close connection
    header("location:index.php"); // redirects to all records page
    exit;
}
else
{
    echo "Error deleting record"; // display error message if not delete
}
?>

I changed in dbconnect.php but that does not help either.

<?php
//connect mysql database
$host = "xxxxxxxxxxxx";
$user = "xxxxxxxxxxxx";
$pass = "xxxxxxxxxxxx";
$db = "xxxxxxxxxxxx";
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_error($con));

?>

2

Answers


  1. On line 7 try to replace $db to $con, because $db on your dbconnect.php is a simple variable and mysqli_query() function, the first parameter expected a mysql object. Loot at this in a first procedural example:

    https://www.php.net/manual/en/mysqli.query.php

    Login or Signup to reply.
  2. include 'dbconnect.php';
    

    // sanitize input parameter
    $id = mysqli_real_escape_string($db, $_GET['id']);

    mysqli_real_escape_string removes all special characters from the input.

    // delete record from database
    $sql = "DELETE FROM tbl_files WHERE id = '$id'";
    if (mysqli_query($con, $sql)) {
    mysqli_close($con);
    header("Location: index.php");
    exit;
    } else {
    echo "Error deleting record: " . mysqli_error($db);
    }

    This should work, I don’t know exactly why because fundamentally it’s the same just formatted differently. But it’s a lot more secure, you should also look in to using environmental variables by doing getenv(‘variable_name’); in the script that needs the variable and putenv(‘variable_name=variable_value’); in the dbconnect script that way you can just have config for credentials and connect in the main php script so that bug fixing is easier.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search