user7120750
user7120750

Reputation:

How to get DB-Connection for my class/function


I'm trying to get a few columns from a certain SQL table, which does work like following:

<?php
include("config.php");

// SELECT DATABASE TO ECHO FROM
$sql = "SELECT * from GuildInformation";

// ECHO FROM THE ^SELECT
$data = $conn->query($sql);

foreach ($data as $row) {
// HERE IS SOME CODE WHICH DOES WORK
}
?>

^this method does work perfectly, now i want to create a function around it:

<?php
include("config.php");

function SelectGuildInfo() {
// SELECT DATABASE TO ECHO FROM
$sql = "SELECT * from GuildInformation";

// ECHO FROM THE ^SELECT
$data = $conn->query($sql);

foreach ($data as $row) {
// HERE IS SOME CODE WHICH DOES WORK
}}
?>

when i call the function SelectGuildInfo(); i get the following error code:

Fatal error: Call to a member function query() on a non-object in /users/l4g/www/84732842323772/submit.php on line 12

Line 12 is: $data = $conn->query($sql);

So when i include("config.php"); into my function it does work again, but i want the database connection to be outside of my function because i'll have more than 1 for this script and just 1 include.


Besides that i'm very new to this whole stuff and actually want to try using a class for my database connection so i came up with this:

    <?php

class dbConn{
    protected static $db;
    private function __construct(){
        try{
            self::$db = new PDO('mysql:host=localhost;dbname=NAME', 'USR', 'PWD');
            self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e){
            echo "Connection Error: " .$e->getMessage();
        }
    }
    public static function getConnection(){
        if(!self::$db){
            new dbConn();
        }
        return self::$db;
    }
}

?>

How do i get to use my class in my script so i dont have to include something for every function i want to use?!

Thank you so much for helping me out!
Having now this code and it runs just perfectly!:)

include("database.class.php");

$db = dbConn::getConnection();

function SelectGuildInfo($db)

Upvotes: 1

Views: 1770

Answers (1)

r_st
r_st

Reputation: 103

Your code doesn't work because $conn inside the SelectGuildInfo() and $conn from your config are two different variables.

In order to make it work, you must add $conn = Database::getInstance() into your SelectGuildInfo (assuming $conn from your working example is instance of Database).

P.S. Please don't use mysql_* functions, use mysqli or PDO instead.

Upvotes: 1

Related Questions