Item behaves as if out of scope

http://pastebin.com/i74Cnws4

After I have tons of errors, but they’re all about database… that for some obscure reason doesn’t want to work. Due to this bug I cannot fetch anything, use anything, everything is null. With brutal debugger, it announces this error:

I replaced actual name with potato.php.

E_WARNING Error in file �potato.php� at line 21: var_dump(): Property access is not allowed yet E_WARNING Error in file �potato.php� at line 21: var_dump(): Property access is not allowed yet E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Property access is not allowed yet E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Property access is not allowed yet E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli E_WARNING Error in file �potato.php� at line 21: var_dump(): Couldn't fetch mysqli object(mysqli)#1 (19) { ["affected_rows"]=> NULL ["client_info"]=> NULL ["client_version"]=> int(50012) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> NULL ["error"]=> NULL ["error_list"]=> NULL ["field_count"]=> NULL ["host_info"]=> NULL ["info"]=> NULL ["insert_id"]=> NULL ["server_info"]=> NULL ["server_version"]=> NULL ["stat"]=> NULL ["sqlstate"]=> NULL ["protocol_version"]=> NULL ["thread_id"]=> NULL ["warning_count"]=> NULL }

Error is printed as many times as you see, even though this function gets called 3 times only as far as I know.

The 21st line is 17th in pastebin. It’s the var_dump($sqli); from within the function.
Tell me what you need to know.

The connection is not within the global scope of the function hence why it is returning NULL.

1 Like

You’re going to get a bunch of database stuff because you var_dumped the database connection. I’m not sure what you were hoping to achieve with that. Did you mean to put a query in there and var_dump the results, but missed those steps?

1 Like

See if variable passes through, it does, but weirdly…

No.

I think everybody misses the point. Let me try another way… I can’t execute this query, why? is the new question. It comes down to this.

And @spaceshiptrooper says that connection is not in scope of function, well how do I make it within the scope?

I don’t see a query in your code.

1 Like

Neither do I…

2 Likes

To be clearer, you need code that looks something like this…

$sqli = new mysqli("127.0.0.1", "root", "", "db");
if (!$sqli) die("Connecting with MySQLi database has failed!");

$stmt = $$sqli->prepare("SELECT field1, field2, field3 FROM testTable WHERE field4 = :value ORDER BY name ASC"); 
$stmt->bindParam(':value', 'ABC');  
$stmt->execute();

$count = $stmt->rowCount();
if ($count == 0) {
   echo "<div>No Record Found!</div>";
}
else 
    echo "<div class='results_found'>" . $count . " results found</div>";

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "<div>" . $row["field1"] . "</div>";
        echo "<div>" . $row["field2"] . "</div>";
    }
}

1 Like

@Gandalf @DaveMaxwell

    echo "THIS IS THE QUERY: >>" . $req . "<< END OF QUERY";
    // Outputs query (that when manually inserted through phpMyAdmin, correctly executes it)
    // THIS IS THE QUERY: >>SELECT id, revision FROM players WHERE id=2726799<< END OF QUERY

Come on… SELECT id, revision FROM players WHERE id=2726799. If you’re trying to help, it would help if you read what I wrote specifically for this reason. This query should work, but doesn’t. It works because I can execute it in phpMyAdmin, it doesn’t work, because $sqli doesn’t work, it doesn’t work because it’s null, it’s null because it’s out of scope, how do I add it to scope? And welcome to square one…

All that line does is echo (i.e. print) the query back to the console/html - IT DOES NOT EXECUTE IT. And wrapping it in a method just adds to the confusion…

I’ll modify the example code I gave you in post #7 to show you how you would need to execute YOUR sql…

$sqli = new mysqli("127.0.0.1", "root", "", "db");
if (!$sqli) die("Connecting with MySQLi database has failed!");

$stmt = $sqli->prepare($req);
$stmt->execute();

$count = $stmt->rowCount();
if ($count == 0) {
   echo "<div>No Record Found!</div>";
}
else 
{
    echo "<div class='results_found'>" . $count . " results found</div>";

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "<div>" . $row["id"] . "</div>";
        echo "<div>" . $row["revision"] . "</div>";
    }
}

or even in your sample code…

<?php
 
    $sqli = new mysqli("127.0.0.1", "root", "", "db");
    if (!$sqli) die("Connecting with MySQLi database has failed!");     // Doesn't drop any errors
 
    var_dump($sqli);   
    // object(mysqli)#1 (19) etc. Regular data as expected
 
 
    function function1($req) {
        global $sqli;       // DEFINED
 
        echo "THIS IS THE QUERY: >>" . $req . "<< END OF QUERY";

        $stmt = $sqli->prepare($req);
        $stmt->execute();

        $count = $stmt->rowCount();
        if ($count == 0) {
                echo "<div>No Record Found!</div>";
        }
        else 
        {
                echo "<div class='results_found'>" . $count . " results found</div>";

                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                        echo "<div>" . $row["id"] . "</div>";
                        echo "<div>" . $row["revision"] . "</div>";
                }
        }
        //        or you could do....
        var_dump($stmt);        // Everything is null WTF?!
    }
 
?>
2 Likes

Your code does not show where function1 is being called which makes it a bit difficult to see what is going on. The scope is fine. The following code works as expected:

error_reporting(E_ALL);

$mysqli = new mysqli('localhost','root','','db');

function function1($req)
{
    global $mysqli;

    $result = mysqli_query($mysqli, $req);
    $row = mysqli_fetch_assoc($result);
    var_dump($row);
}
function1('SELECT * FROM users WHERE id = 1');

I am speculating here but I suspect you have multiple files and are including things out of order.

1 Like

Yea, nobody seems to read my posts. So for those that do, I’ll solve it on my own. I really don’t have time for 20 posts and I won’t waste your time either, explaining the same exact issue, and people giving me 19 solutions, that will create exactly same 19 errors messages.

I’m done. Here’s the heart for all of you. Good job, 5 variations of the same error.

It’s because they are suspicious with your comments you made in your snippet. What you need to do is either inject the connection into the function of you need to make the connection global.

1 Like

Here’s a snippet I tested and works. I didn’t get a chance to look at your whole snippet before you removed it from your pastebin.


NOTE


DO NOT TAKE THIS SNIPPET AS LITERAL!!


You should write your own, this is just a sample snippet I tested with what I was trying to explain.


<?php
// Create the database connection
// MySQLi_ OOP is as is
// {host}, {username}, {password}, {database}
$mysqli = new mysqli('localhost', 'root', 'root', 'sitepoint');

// Check whether the connection failed or not
if($mysqli->connect_errno) {

    die('Connecting with MySQLi database has failed!');

}

// Create the function and inject 3 variables into it
// First variable is ID of the requested user
// Second variable is the database connection, we can just reference it using $mysqli
// Third variable is the SQL statement
function function1($id, $mysqli, $sql) {

    $prepare = $mysqli->prepare($sql); // Prepare our SQL statement
    $prepare->bind_param('i', $id); // Bind the variable with its appropriate data type || See below for data types
    $prepare->execute(); // Execute the prepared statement
    $prepare->store_result(); // Store the result for later checking

    // Data types for mysqli_* are as is
    // i = integer (only whole numbers like 0, 1, 2, 3, 4, 5)
    // s = string (can be anything from numeric numbers to letter characters)
    // b = blob (never used it so I can't tell you what it is exactly, I believe you can store images in this data type)
    // d = double (just like an integer, but also allows half numbers like 0, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 1.1, 1.2, 1.3, 1.4, 1.5)

    // Check whether the data returns anything using num_rows
    if($prepare->num_rows) {

        $prepare->bind_result($id, $first_name, $last_name); // Create and append variables based on the columns you specified

        // Loop the data in a while loop
        while($prepare->fetch()) {

            // Printing out the HTML stuff we want

            print('<strong>ID:</strong> ' . $id);
            print('<br />');
            print('<strong>First Name:</strong> ' . $first_name);
            print('<br />');
            print('<strong>Last Name:</strong> ' . $last_name);

        }

    } else {

        // The data does not exist, so we should tell the user
        print('No such data returned');

    }

}

// Call the function by injecting the 3 parameters we want
// First parameter is based on the ID from the URL, this is a shorthand version for checking if the $_GET parameter - id exists
// Second parameter is our database connection, we inject it this way so that our function can use it
// Third parameter is our SQL statement
function1(isset($_GET['id']) ? $_GET['id'] : 0, $mysqli, 'SELECT id, first_name, last_name FROM users WHERE id = ? LIMIT 1');
3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.