Hi all,

I've been playing around with this for 30 odd minutes now and basically been making a right fool of myself...

I want to make a function called userInfo() that uses the users email address, stored in $_SESSION['auth'];, to get any information required from sql. I'm using MySQLi and I'm very new to it (started this morning).

So basically, the function userInfo(); in config.php should create an array of that users info. When I need the username of the user I should be able to type $userInfo['username']; or $userInfo['landline']; to get the landline of the user anywhere on a page that has config.php included.

Now looking at the below example from php.net I know I need an associative array. What I don't udnerstand is keeping the array alive for the pages lifespan so that I can easily display array values anywhere. I've dedited the query below to match my actual SQL query.

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT * FROM users WHERE email = '".$_SESSION['authenticated_user']."'";
$result = $mysqli->query($query);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);

/* free result set <--- Do I just delete this? */ 
$result->free();

/* close connection <--- Does closing the connection destroy the retrieved values? */
$mysqli->close();
?>

Can anyone please help?

Thanks in advance!

That's already page scope, and you could use $row anywhere on the page.
If $row appeared in a function, you could only use it within that function.
The scope is important, perhaps you should provide the code you're using which causes your actual problem.

Everything looks good, but just to make sure that you can access your data globally you might want to do something like this.

<?php
//this is config.php
//inclusion of this file will give you access to an array called $userInfo
//you can get information about the user by accessing this array using a key
//Ex: $userInfo["username"]
//Warning: the keys that can be used on userinfo have to match the column names
//in the table 'users'

function userInfo() {
    global $userInfo;

    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");
    $query = "SELECT * FROM users WHERE email = '".$_SESSION['authenticated_user']."'";
    $result = $mysqli->query($query);

    $userInfo = $result->fetch_array(MYSQLI_ASSOC);
    $result->free(); 
    $mysqli->close();
}

//initialize userInfo
$userInfo = array(); //i don't think this is needed, but i always do this just to be safe
userInfo();

In your next file you can access $userInfo like this:

<?php
include_once("/pathto/confg.php");
function displayUserEmail() {
    //this is how you would do it in functions
    global $userInfo
    return $userInfo["email"];
}

//this is how you can do it outside of a function
$userInfo["email"];

One downfall of doing it this way is, every time you include config.php you will hit your database with a query. It might not be the best choice depending on your setup. This is programming and there are lots of ways to do the same thing. It's important to find what's best for your situation.

As for your questions about mysqli, you might want to check out the documents.
http://php.net/manual/en/mysqli-result.fetch-array.php

commented: Very useful! +2

Didn't refresh before posting this, thanks for reponses I'll look into it and post back soon.

M.

Thanks for that, it makes a lot of sense nexocentric. One thing I would like to be aware of is avoiding this all over the shop: $mysqli = new mysqli("localhost", "my_user", "my_password", "world");. I believe the term is OOP - how can I declare my DB connection once in the config and use it wherever on my website? Does a simple variable do the trick or do I turn that into a function and just delcare the function before any DB query?

As for:

One downfall of doing it this way is, every time you include config.php you will hit your database with a query.

Would it be better to define these once when the user logs in? Can you store an array as a session? Would this be the best method? I really appriciate your feedback so thank you.

class SQLink
{
  public $sqlink;
  // make a connection...
  public function __construct( $host="localhost", $u="root", $p="", $db="" )
  { // I can't save you from this.
    $sqlink = new mysqli( $host, $u, $p, $db );
  }

  // If you want to call query with the -> operator, be careful
  // link->query [does], returns reply.
  public function __get( $q )
  {
    return $sqlink->query( $q );
  } // That's all.

  // If you're not comfortable with the language, it's probably safer for you
  // to route query this way.
  public function query( $q )
  {
    return $sqlink->query( $q );
  }

};

$sql = new SQLink( "host", "uname", "pass", "db" );
$table = "arbitrary";
$q = "SELECT * FROM $table";

$res = $sql->$q;
$res = $sql->query( $q );

P.S. In case it's not clear, you'd instantiate this in a global include file for your purpose.
P.P.S. The object doesn't have to be global to be in scope.

I've never applied code like this before I'm afraid @Unimportant. I think my issue here is no experience with OOP, poor experience with functions and no experience with classes! (Shocking... i know.).

I currently have this function in config.php:

function userInfo() {
global $userInfo;
$mysqli = new mysqli("localhost", "root", "", "studybubble");
$query = "SELECT * FROM users WHERE email = '".$_SESSION['auth']."'";
$result = $mysqli->query($query);
$userInfo = $result->fetch_array(MYSQLI_ASSOC);
$result->free();
$mysqli->close();
}

I've included config.php into index.php. In index.php I have called the function userInfo(); and I have echoed this variable: $userInfo['authuser'], which should print the current visitors username. Instead I'm getting this error:

[12-Jul-2013 12:27:12 UTC] PHP Fatal error: Call to a member function fetch_array() on a non-object in C:\xampp\htdocs\sb\inc\config.php on line 31

Line 31 is: $userInfo = $result->fetch_array(MYSQLI_ASSOC);

Any ideas? I've played around with it but just got a series of different errors.

I'm not lazy though! I just purchased a book on MySQLi!

From the example given in PHP Manual mysqli::query

if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }

If you do this, it may give you some insight.

commented: Helpful, but already had it in :) +2

You might want to try and catch errors on each line of your code to make sure that nothing's failing before you attempt to make the query.

The link I provided above should have some extra information.

Hi all,

I was already getting the error - mentioned it above?

[12-Jul-2013 12:27:12 UTC] PHP Fatal error: Call to a member function fetch_array() on a non-object in C:\xampp\htdocs\sb\inc\config.php on line 31.

Line 31 is: $userInfo = $result->fetch_array(MYSQLI_ASSOC);

I'm currently researching Call to a member function fetch_array() on a non-object in C:\xampp\htdocs\sb\inc\config.php on line 31

I think this may be a communication breakdown due to our differing native language.

I understand that PHP is catching your error, but you need to ask MySQL what the problem is instead.
I intuited that query did not return a valid result, which is why I attempted to make you check that case.
You'll want to make sure that $result is in fact a valid object.

Sorry - I had to run out for a while.

Okay I'll try this now, I understand where you're coming from and will see if I have any luck.

M.

There is nothing being reported? All I have is Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\sb\inc\config.php on line 36.

I have change the code by adding a prepare the the query and then executing it. Reports same error.

        function userInfo() {
        global $userInfo;

        $user_email_ident = $_SESSION['auth'];

        $mysqli = new mysqli("localhost", "root", "", "studybubble");

            if (!$mysqli->query("SET @a:='this will not work'")) {
                printf("Error: %s\n", $mysqli->error);
                }

        $query = $mysqli->prepare("SELECT * FROM `users` WHERE `email` = '$user_email_ident'");
        $result = $query->execute();
        $userInfo = $result->fetch_array(MYSQLI_ASSOC);
        $result->free();
        $mysqli->close();
        }

Woo progress!

new error:

Fatal error: Call to a member function fetch_array() on a non-object in C:\xampp\htdocs\sb\inc\config.php on line 37

Line 37:
$userInfo = $result->fetch_array(MYSQLI_ASSOC);

I am working on this intensely but posting here incase the answer is obvious to someone with greater exeprience.

Ok ok ok, I really wanted you to figure this out on your own... but it's almost like the typo is holding you back.
Are you sure the connection is properly established?

You left your original query which causes the program to die, you never get to see the output of ->error

Solved! Thank you all :)

The problem was calling $userInfo = array(); after calling the function userInfo(); as it of course destroyed the variables stored value. It was left voer from old code. Unbelieveable! Thanks for all your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.