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.

3
  • 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. Commented Mar 18, 2021 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. Commented Mar 18, 2021 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. Commented Mar 18, 2021 at 15:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.