NamePros.Com (http://www.namepros.com/)
-   CODE (http://www.namepros.com/code/)
-   -   2 handy MySQL functions! (http://www.namepros.com/code/236229-2-handy-mysql-functions.html)

Barrucadu 09-09-2006 04:49 AM

2 handy MySQL functions!
 
Functions:
set_database_vars($mysql_server, $mysql_username, $mysql_password, $database_name) - Stores the MySQL conenction information. Returns an error message if it fails.

sql($query) - Creates a mysql connection, queries the database, and closes the conenction. Returns the results if sucecssful, if it fails, it returns an error message.

Code:
PHP Code:
<?php

$mod_db
['Server'] = '';
$mod_db['Username'] = '';
$mod_db['Password'] = '';
$mod_db['Name'] = '';

function
set_database_vars($server, $username, $password, $name){
    
$mod_db['Server'] = $server;
    
$mod_db['Username'] = $username;
    
$mod_db['Password'] = $password;
    
$mod_db['Name'] = $name;
    
    return
true;
}

function
sql($query){
    
mysql_connect($mod_db['Server'], $mod_db['Username'], $mod_db['Password'], $mod_db['Name'])or return 'Error 1 - Please check your database variables are correct.<br /><br />';
    
$result = mysql_query($query)or return 'Error 2 - Please check your SQL query is correct for your version of MySQL.<br /><br />';
    return
$result;
    
mysql_close();
}

?>


Handy if you need to do a lot of queries - just include that code in a seperate file and you can query in 1 line of code.

sukantab 09-09-2006 06:37 AM

If I need to use queries extensively, I would create a global connection variable dbconn. Because connecting to a db is always memory consuming.
Also, don't close conn. and in your code the close will not be executed because you are doing a return before it.

Please send me your comments....

Code:
<?php $mod_db['Server'] = ''; $mod_db['Username'] = ''; $mod_db['Password'] = ''; $mod_db['Name'] = ''; $dbconn = null; function set_database_vars($server, $username, $password, $name){ $mod_db['Server'] = $server; $mod_db['Username'] = $username; $mod_db['Password'] = $password; $mod_db['Name'] = $name; return true; } function sql($query){ if($dbconn=null) { $dbconn = mysql_connect($mod_db['Server'], $mod_db['Username'], $mod_db['Password'], $mod_db['Name'])or return 'Error 1 - Please check your database variables are correct.<br /><br />'; } $result = mysql_query($query)or return 'Error 2 - Please check your SQL query is correct for your version of MySQL.<br /><br />'; return $result; // mysql_close(); } ?>

gauravmm 09-10-2006 06:01 AM

Thanks a lot Saved me a lot of coding

boebi 10-14-2006 06:53 AM

omg, you all know so much about php.. i wish i had the same knoweledge.


All times are GMT -7. The time now is 03:46 AM.
Site Sponsors
Advertise your business at NamePros

Powered by: vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 2.4.0