1

I already tried other solutions from similar questions but it seems that nothing worked. Like the title says, the query I need to execute on my db works fine on phpMyAdmin, but it doesn't work when used inside a php function. This is the code in common_functions.php:

function eliminaRistorante($id_ristorante) {
    global $conn;

    // query su ristorante
    $sql = "DELETE FROM ristorante WHERE id_ristorante = $id_ristorante";

    echo $sql;

    if($conn->query($sql) === TRUE) {
        return true;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        return false;
    }
}

This is the code in hold.php:

include('includes/logic/common_functions.php');

if (isset($_POST['del'])) {
    $id_ristorante = $_POST['del'];

    eliminaRistorante($id_ristorante);
    header('location: admin/ristorante.php');
}

I put an echo statement to see if the query was effectively correct. This is the output:

DELETE FROM ristorante WHERE id_ristorante = 5 Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\projects\db_ristorante\includes\logic\common_functions.php:57 Stack trace: #0 C:\xampp\htdocs\projects\db_ristorante\hold.php(8): eliminaRistorante('5') #1 {main} thrown in C:\xampp\htdocs\projects\db_ristorante\includes\logic\common_functions.php on line 57

Lastly, I tried these solutions: MySql query not in working in PHP but works in phpMyAdmin

Inside that question the user kindly shared other solutions that I considered too.

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
Sergio
  • 31
  • 9
  • 1
    `Call to a member function query() on null` does not mean there was a problem with your query, it means that `$conn` was null. – CBroe Mar 18 '21 at 11:46
  • 1
    Better to pass `$conn` into your function as a parameter than to use a global variable. Also you need to look at prepared statements rather than concatenating strings into queries. – droopsnoot Mar 18 '21 at 11:48
  • Thanks to both I got the reason why the error popped up, I did as @droopsnoot suggested and passed $conn as a parameter, that solved the problem. – Sergio Mar 18 '21 at 15:45

1 Answers1

1

Uncaught Error: Call to a member function query() on null in

your $conn Object is null. You did not initialise a PDO instance.

Here is a introduction, on how to do that, PHP The Right Way - PDO

jpgerdeman
  • 82
  • 6