Tough question. Setting up modular code. Connections

3 replies
Perhaps I've being going about this all wrong, fair enough but essentially what I'm trying to do is place all my db connection info on another page `connect.php`. The idea is to then setup a function (below) which can then be called in *once* on my class files for use within a global variable which can then be utilised by all the methods within the class.

Before we go further I want to add that I 'might' need to return an array of mysqli_connect(x.x.x.x) in my dbcon() function for the mysqli code to operate as intended but we'll get on to that later.

Here's what's going on so far. Had some help on this already so don't give me all the credit.


connect.php

function dbcon()
{

static $conn;

if (!$conn)
{
$host = 'localhost';
$username = 'x';
$password = 'x';
$dbname = 'x';
$conn = mysqli_connect($host , $username , $password ,$dbname);
}

return $conn;
}


On my class file this is how I am attempting to initiate it.
Code:
    require_once("assets/configs/connect.php"); 
    
    (); //Line 5
    
    class myclass {

    Function (some functions)
    {
Results in :
Code:
> Notice: Undefined variable: conn in C:xampphtdocscatsassetsincludescatclass.php on line 5

> Fatal error: Call to a cat function dbcon() on a non-object in C:xampphtdocscatsassetsincludescatclass.php on line 5
Can anyone shed some light on what I'm doing wrong here, and crucially point me in the right direct to resolving this. Ideally, I don't want to have to back track on the approach I'm taking.
#code #connections #modular #question #setting #tough
  • Profile picture of the author aronprins
    Code:
    > Notice: Undefined variable: conn in C:xampphtdocscatsassetsincludescatclass.php on line 5
    
    > Fatal error: Call to a cat function dbcon() on a non-object in C:xampphtdocscatsassetsincludescatclass.php on line 5
    Hey,

    Im not an expert but the code looks fine to me.
    Maybe it's because there are no /'s in the folders?
    Just pointing it out, hope this helps!

    Cheers,
    Aron Prins
    {{ DiscussionBoard.errors[8429191].message }}
  • Profile picture of the author phpg
    The code was cut out by the forum, but i'm guessing your Line 5 actually looks like this:

    $conn->dbcon(); //Line 5

    This is wrong, should be:

    $conn = dbcon();
    {{ DiscussionBoard.errors[8430182].message }}
  • Profile picture of the author SteveJohnson
    If you want to brew your own db class, it helps to look at ones that are already around. Look at EZSql by Justin Vincent, or look at the WordPress database class found in wp-includes/wp-db.php.
    Signature

    The 2nd Amendment, 1789 - The Original Homeland Security.

    Gun control means never having to say, "I missed you."

    {{ DiscussionBoard.errors[8433948].message }}

Trending Topics