I'm trying to get a handle on PDO. I've been using mysql_real_escape_string to handle database inserts, updates and so forth currently. I feel like I'm about six years behind when it comes to this stuff.
The current way that I deal with database connections is I have a config file that contains the host name, db name, uersname and password. Then, I have a dbConnect file that does the actual connection. See below.
$MYSQL_ERRNO = '';
$MYSQL_ERROR = '';
function db_connect() {
global $dbhost, $dbusername, $dbuserpassword, $default_dbname;
global $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect($dbhost, $dbusername, $dbuserpassword);
if(!$link_id) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Conection failed to the host $dbhost.";
return 0;
}
else if(empty($dbname) && !mysql_select_db($default_dbname)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
function sql_error() {
global $MYSQL_ERRNO, $MYSQL_ERROR;
if(empty($MYSQL_ERROR)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
}
return "$MYSQL_ERRNO: $MYSQL_ERROR";
}
Below is what I'm coming up with for PDO. How bad is it?
function db() {
global $dbhost, $dbusername, $dbuserpassword, $default_dbname;
static $conn;
if (!isset($conn)) {
$conn = new PDO("mysql:host=$dbhost;dbname=$default_dbname", $dbusername, $dbuserpassword);
}
return $conn;
}
A select query and how I would retrieve results.
$rows = db()->query("SELECT users_id FROM users")->fetchAll();
foreach ($rows as $row) {
echo $row['users_id'] . '<br />';
}
One of the things I'm not certain about is the try/catch. I don't have it above, but every example I found uses it. I have a feeling my method above is incorrect. Also, most of the examples I've found always have the INSERT, UPDATE or SELECT inside the try/catch. Does this have to be, or can queries exist outside?