phantom phantom - 4 months ago 19
MySQL Question

putting sql query in function php

I am trying to put an SQL query in a PHP function but am getting the following error in the terminal

Fatal error: Call to a member function query() on a non-object in /Users/file.php on line 18


Please see line 16 to 22 of my PHP code below:

function testFunction() {
$sql = "SELECT * FROM testNumber WHERE test = '1'"
$result = $conn->query($sql);
return $result->num_rows;
}

$testVariable = $testFunction();
echo $testVariable;

Answer

The $conn is not accessible in the function scope,

You need somehow to access the $conn variabel to use it.

You have two options, Pass the $conn as function argument.

function myFunc($conn)

or use the global keyword. (See reference for Variables Scope)

Passing Connection:

   function testFunction($conn) {
         $sql = "SELECT * FROM testNumber WHERE test = '1'"
         $result = $conn->query($sql);
         return $result->num_rows;
    }

    $conn = new mysqli(,,,);
    $testVariable = testFunction($conn);
    echo $testVariable

Using global:

function testFunction() {
     global $conn;
     $sql = "SELECT * FROM testNumber WHERE test = '1'"
     $result = $conn->query($sql);
     return $result->num_rows;
}

$testVariable = testFunction();
echo $testVariable