开发者

PHP: newbie question - open database

开发者 https://www.devze.com 2023-02-17 16:52 出处:网络
I\'ve written some simple functions for database handling like this: function dbOpen($db) { $username = \"admin\";

I've written some simple functions for database handling like this:

function dbOpen($db)
{
    $username = "admin";
    $password = "pass";
    $hostname = "localhost";    
    $db = mysql_connect($hostname, $username, $password)
}

function dbClose($db)
{
    mysql_close($db);
}

What I want to do is get access to the variable I passed to the dbOpen function like:

dbOpen($myDB);
$result = mysql_query('SELECT * FROM my_tbl',$myDB);

Howev开发者_JAVA技巧er, for some reason this function won't initialize $myDB. Does anyone have any ideas what I'm doing wrong?


If you want to do that, you need to set up your database functions to take that variable passed as a reference. This here explains it.


function dbOpen($db) { ... } won't affect the $db passed to it. If you want to do that, you might try passing by reference, like function dbOpen(&$db) { ... }.

Better, though, would be to return the handle you just opened. That is, instead of trying to set $db, just return $db; -- and in the code calling it, be like $myDB = dbOpen();. (Note, i'm not mentioning a parameter to dbOpen -- you don't need it, since its only purpose was to be a return value.)


Whilst this might not be the exact answer you're looking for - and may be overkill - I'd like to explain how you might do this with classes in PHP. You'd do something like this:

<?php

class Database {

    private $db;

    function __construct() {
        $username = "admin";
        $password = "pass";
        $host = "localhost";
        $this->db = mysql_connect($hostname, $username, $password);
    }

    function close() {
        mysql_close($this->db);
    }

    function query($sql) {
        return mysql_query($sql, $this->db);
    }

}

?>

That __construct() function is called a constructor, and is run when you make a new instance of that class. Here's an example of creating and using a new instance of your database class:

<?php

$d = new Database();
echo $d->query('SELECT * FROM my_tbl');

?>

In basic terms, the arrow (->) after $d, means that you're accessing the method query in the object $d (ie. your database object). Hope this "Object-Oriented" PHP isn't too much info for a beginner - you may want to read this swift introduction to the underlying concepts.

0

精彩评论

暂无评论...
验证码 换一张
取 消