faqts : Computers : Programming : Languages : PHP : kms : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

39 of 1053 people (4%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

how to make a database query within a function

Aug 22nd, 2001 07:28
marc ap neb, prince lin,


1. connect to the db server (if you haven't already opened a persistant 
connection)
2. select a db
3. make your query

eg
function connect($server,$database,$username,$password)
{
    //this will open a persistent connection to a mysql server
    if (!($link = @mysql_pconnect($server, $username, $password))){
        echo "Could not connect to server $server.<br>";
        return false;
    }
    if (!($db = @mysql_select_db($database, $link))){
        echo "Could not connect to database $database.";
        return false
    }
    return $db;
}

then 

function do_query()
{
    $sql = "SELECT * from table_name;";
    $result = mysql_query($sql);
    // do something with the result
}

this will use the open connection.  

If you don't have persistent connection, then you will have to create a 
connection for the query and use the optional parameter in mysql_query, 
similarly with mysql_db_query to access another db. something like


function do_query($server, $database, $username, $password)
{
    if (!($link = @mysql_connect($server, $username, $password))){
        echo "Could not connect to server $server.<br>";
        return false;
    }
    if (!($db = @mysql_select_db($database, $link))){
        echo "Could not connect to database $database.";
        return false
    }
    $sql = "SELECT * from table_name;";
    $result = mysql_db_query($db,$sql,$link);
    // do something with the result
}
this is ok if you are making a single query and don't need to use the 
db connection much as there is quite an overhead in opening 
connections, hence the persistent connection feature