I'm a PHP newbie, and started with the tutorials on php-mysql-tutorial.com, and since bought O'Reilly's "Learning PHP & MySQL" to further my edumacation. I really like the language, and coming from trying to learn C and C++ on my own (a little difficult, I might add), I'm finding PHP pretty easy so far.
My problem, being new to this, is that I'm ignorant of many functions some vets wouldn't even think about while they utilized them. That said, I'm presently working on a simple DB script that connects to a database, and submits a supplied query.
So, my main question is: Am I reinventing the wheel? Also: Is there something else I could do to improve this?
Here's what I've got so far...
Code: Select all
<?php
/**
* Filename: db_login.php
*/
define('db_hostname', 'localhost');
define('db_database', 'dbname');
define('db_username', 'username');
define('db_password', 'password');
// 0 = error silently, 1 = simple errors, 2 = verbose errors.
$db_error_level = 0;
?>Code: Select all
<?php
/**
* Filename: sql.php
*/
require_once('db_login.php');
/**
* Fx sendQ(SQL query)
* Submits query and returns SQL resource, then closes the DB connection.
* Will output mysql_error() reports if db_verbose_errors (db_login.php) is true, which
* a security risk, since it displays important DB information.
* Will output simple errors if db_silent_errors (db_login.php) is false.
* NOTE: db_verbose_errors is checked before db_silent_errors, so if verbose AND silent
* errors are enabled, errors will be printed verbosely.
*
* @param string $query
* @return SQL_Resource
*/
function sendQ($query)
{
global $db_verbose_errors;
$connection = @mysql_connect(db_hostname, db_username, db_password);
if(!$connection)
{
qError("Could not connect to the SQL host.");
}
else
{
if(!(@mysql_select_db(db_database, $connection)))
{
qError("Could not select the database.");
}
else
{
if(!($result = @mysql_query($query)))
{
qError("Could not execute query.");
}
}
}
@mysql_close($connection);
return $result;
}
/**
* Fx qError($arg)
* Prints a SQL error. Verboseness depends on $db_error_level set in (db_login.php).
*
* @param string $arg
* @return none
*/
function qError($arg)
{
global $db_error_level;
switch($db_error_level)
{
case 0:
die();
break;
case 1:
die("$arg <br />". mysql_error());
break;
case 2:
die("$arg <br />");
break;
default:
break;
}
}
?>